Reputation: 380
I want to pack the lowest two bytes of an integer into another in integer, an stuck at this
for ( int i = 0; i < 8 ; i ++){
if ((bitmask & ( 1 << i)))
result |= 1 >> i;
}
Upvotes: 3
Views: 2452
Reputation: 758
If i understood you correctly sufficient solution should be this:
another_integer = first_integer & 0xFFFF // which is 65536, which is 2^16 so 0000000011111111 binary (for 4 byte integer)
That way you would assign value of two lower bytes of first_integer to the another_integer by using simple AND mask:
0101110011101010
0000000011111111 AND
----------------
0000000011101010
Upvotes: 1
Reputation: 213306
Endian-independent solution:
x = ((y >> 0) & 0xFF) |
((y >> 8) & 0xFF);
Upvotes: 4