I am stuck with a simple problem. Here is the code:
int main(int argc, char **argv)
{
char buf[2] = {0xd, 0x1f};
unsigned int a;
a = ((buf[1] << 8) & 0xFF00) | buf[0];
printf("%d\n",a);
return 0;
}
The value in a that I need is 0x1FD(509) but when I ran the above program the output in a is 0x1F0D(7949) .
How can I achieve this ?
EDIT :
Ok let me clarify . I am doing a project where I receive the data as shown in the code snippet.To simplify I have declared them local . The main thing is I want the data to be interpreted as 0x1FD(509) .
The program does what you asked it to do. The source of your confusion is in the 0xd constant, which is actually 0x0d, because char is eight bits. Packing it together with 0x1f as you do should produce 0x1f0d, and it does.
You need
char buf[2] = {0xfd, 0x01};
That is, you need to "pack" the bits from right to left.
This is clearer if you pad the desired value with zeroes, so it's written as a string of complete bytes:
0x1FD = 0x01FD = (0x01 << 8) | 0xFD
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With