Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

packing bits into an integer in C++

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;
     }
like image 403
nevanom Avatar asked Feb 21 '26 18:02

nevanom


1 Answers

Endian-independent solution:

x = ((y >> 0) & 0xFF) |
    ((y >> 8) & 0xFF);
like image 134
Lundin Avatar answered Feb 23 '26 06:02

Lundin