Reputation: 89
Can someone please tell me what do these lines of code do
*(a++) = (int)((value >> 16) & 0xFF) ;
*(a++) = (int)((value >> 8) & 0xFF) ;
*(a++) = (int)((value & 0xFF)) ;
I understand that it checks the value, if it is much greater than 16 it converts it to type int and if it is much smaller than 8 does the same. But what does the
& 0xFF
and *(a++)
do?
Upvotes: 0
Views: 150
Reputation: 578
*(a++) = (int)((value >> 16) & 0xFF) ;
is like:
aIntValue = value/65536;
aIntBalue = a%256;
*(a++) = (int)((value >> 8) & 0xFF) ;
is like:
aIntValue = value/256;
aIntValue = a%256;
*(a++) = (int)((value & 0xFF)) ;
is like:
aIntValue = a%256;
At the end of the code, either code assign the aIntValut to the value pointed to the pointer 'a' and next the pointer is moved to the next element.
Upvotes: 1
Reputation: 8145
Given:
char data[10];
uint32_t value = 0x61626364; // 'abcd'
char *a = data;
*(a++) = (int)((value >> 24) & 0xFF);
*(a++) = (int)((value >> 16) & 0xFF);
*(a++) = (int)((value >> 8) & 0xFF);
*(a++) = (int)(value & 0xFF);
*(a++) = ':';
*((uint32_t *)a) = value;
a+=4;
*(a++) = 0;
printf("%s\n", data);
I get (on my intel box, which is a little endian system):
abcd:dcba
So this is ensuring that the bytes of an integer are in an platform-independent form (choosing big endian as the byte format).
Now, for:
*(a++) = (int)((value >> 16) & 0xFF);
we have:
0x61626364 -- value
0x00006162 -- value >> 16 : shifted 2 bytes
0x00000062 -- (value >> 16) & 0xFF : last byte only
Upvotes: 1
Reputation: 182619
I understand that it checks the value
It doesn't check anything, it's not like the <<
symbol in math which means "much smaller". To break down this line:
*(a++) = (int)((value >> 16) & 0xFF);
>>
) shifts value
16 times to the right&
) ands the result with 0xFF
, thereby discarding everything to the lefta
a
point to some "next" elementUpvotes: 2
Reputation: 11910
(value>>16)
No it is not much greater.
It is shift right by 16 bits.
But dividing it by 2 exatly 16 times makes it much smaller than before.
val&0xff makes a solution if it is divisible by 256. For example: if val&0xff is different than zero, than it is not divisible by 256
Upvotes: 1