How to print a four character hexadecimal in C? - c

for (int x= 7; 0<=x; x--) {
size_t x_val = ((1<<4)-1) & io>>x*4;
printf("%lX", x_val);
Trying to print a hexadecimal number here after converting it from integer. While the conversion is successful, the output is FFFFFFCD instead of the desired output FFCD. How can I limit maximum 4 characters to be printed?

to print a four character hexadecimal
Limit value to the [0...0xFFFF] range.
Print 4 digits padded with zeros with the correct specifier.
Example
unsigned masked_value = io & 0xFFFF;
printf("%04X\n", masked_value);

Try this one,
You can use hh to tell printf that the argument is an unsigned char. Use 0 to get zero padding and 4 to set the width to 4. x or X for lower/uppercase hex characters.
uint8_t a = 0x0a;
printf("%02hhX", a); // Prints "0A"
printf("0x%02hhx", a);

Related

ASCII stored in String to Number in Arduino

I have the the ascii value of the integer number stored in string variable in arduino sketch and I want to convert it to the integer number. How do I do this?
String a = "59"; // or, 0x32, ASCII value of integer number 2
const char * s = &a[0];
int num = atoi(s);
I expected the num to be 2 (the number corresponding the ascii 59)
But, when I print 'num' in serial monitor, I am getting it to be 59 (Not 2).
You need to cast your integer to char, when sending it. As in:
int x = atoi("50");
Serial.write((char)x);

How to print in HEX format the MSBs bits when they're equal to 0

I need to print variables using HEX format.
The problem is when my variables are little the MSBs equal 0 so they are not printed.
ex: uint16_t var = 10; // (0x000A)h
-> I need to print "000A" but no matter what I do it always prints just 'A'
How could I get it to work?
You can add a leading 0 to the width specifier in order to force printf to add leading zeros (at least, you can in C and C++ - not entirely sure about other languages that use the function).
For example, in C, the following:
#include <stdio.h>
#include <stdint.h>
int main()
{
uint16_t a = 10; // 0xA
printf("%04X\n", a);
// ^ width specifier: display as 4 digits
// ^ this signals to add leading zeros to pad to at least "n" digits
return 0;
}
will display:
000A

using strtol on bytes stored in char array

I'm trying to extract 2nd and 3rd byte from a char array and interpret it's value as an integer. Here in this case, want to extract 0x01 and 0x18 and interpret its value as 0x118 or 280 (decimal) using strtol. But the output act len returns 0.
int main() {
char str[]={0x82,0x01,0x18,0x7d};
char *len_f_str = malloc(10);
int i;
memset(len_f_str,'\0',sizeof(len_f_str));
strncpy(len_f_str,str+1,2);
printf("%x\n",str[1] & 0xff);
printf("%x\n",len_f_str[1] & 0xff);
printf("act len:%ld\n",strtol(len_f_str,NULL,16));
return 0;
}
Output:
bash-3.2$ ./a.out
1
18
act len:0
What am I missing here? Help appreciated.
strtol converts an ASCII representation of a string to a value, not the actual bits.
Try this:
short* myShort;
myShort = (short*) str[1];
long myLong = (long) myShort;
strtol expects the input to be a sequence of characters representing the number in a printable form. To represent 0x118 you would use
char *num = "118";
If you then pass num to strtol, and give it a radix of 16, you would get your 280 back.
If your number is represented as a sequence of bytes, you could use simple math to compute the result:
unsigned char str[]={0x82,0x01,0x18,0x7d};
unsigned int res = str[1] << 8 | str[2];

How to display hexadecimal numbers in C?

I have a list of numbers as below:
0, 16, 32, 48 ...
I need to output those numbers in hexadecimal as:
0000,0010,0020,0030,0040 ...
I have tried solution such as:
printf("%.4x",a); // where a is an integer
but the result that I got is:
0000, 0001, 0002, 0003, 0004 ...
I think I'm close there. Can anybody help as I'm not
so good at printf in C.
Thanks.
Try:
printf("%04x",a);
0 - Left-pads the number with
zeroes (0) instead of spaces, where
padding is specified.
4 (width) - Minimum number of
characters to be printed. If the
value to be printed is shorter than
this number, the result is right justified
within this width by padding on the left
with the pad character. By default this is
a blank space, but the leading zero we used
specifies a zero as the pad char.
The value is not truncated even if the result is
larger.
x - Specifier for hexadecimal
integer.
More here
i use it like this:
printf("my number is 0x%02X\n",number);
// output: my number is 0x4A
Just change number "2" to any number of chars You want to print ;)
Your code has no problem. It does print the way you want. Alternatively, you can do this:
printf("%04x",a);
You can use the following snippet code:
#include<stdio.h>
int main(int argc, char *argv[]){
unsigned int i;
printf("decimal hexadecimal\n");
for (i = 0; i <= 256; i+=16)
printf("%04d 0x%04X\n", i, i);
return 0;
}
It prints both decimal and hexadecimal numbers in 4 places with zero padding.

Hex to Decimal conversion in C

Here is my code which is doing the conversion from hex to decimal. The hex values are stored in a unsigned char array:
int liIndex ;
long hexToDec ;
unsigned char length[4];
for (liIndex = 0; liIndex < 4 ; liIndex++)
{
length[liIndex]= (unsigned char) *content;
printf("\n Hex value is %.2x", length[liIndex]);
content++;
}
hexToDec = strtol(length, NULL, 16);
Each array element contains 1 byte of information and I have read 4 bytes. When I execute it, here is the output that I get :
Hex value is 00
Hex value is 00
Hex value is 00
Hex value is 01
Chunk length is 0
Can any one please help me understand the error here. Th decimal value should have come out as 1 instead of 0.
Regards,
darkie
My guess from your use of %x is that content is encoding your hexademical number as an array of integers, and not an array of characters. That is, are you representing a 0 digit in content as '\0', or '0'?
strtol only works in the latter case. If content is indeed an array of integers, the following code should do the trick:
hexToDec = 0;
int place = 1;
for(int i=3; i>=0; --i)
{
hexToDec += place * (unsigned int)*(content+i);
place *= 16;
}
content += 4;
strtol is expecting a zero-terminated string. length[0] == '\0', and thus strtol stops processing right there. It converts things like "0A21", not things like {0,0,0,1} like you have.
What are the contents of content and what are you trying to do, exactly? What you've built seems strange to me on a number of counts.

Resources