Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I store 4 char into an unsigned int using bitwise operation?

I would like to store 4 char (4 bytes) into an unsigned int.

like image 932
M.ES Avatar asked Apr 24 '11 17:04

M.ES


2 Answers

You need to shift the bits of each char over, then OR combine them into the int:

unsigned int final = 0;
final |= ( data[0] << 24 );
final |= ( data[1] << 16 );
final |= ( data[2] <<  8 );
final |= ( data[3]       );

That uses an array of chars, but it's the same principle no matter how the data is coming in. (I think I got the shifts right)

like image 189
ssube Avatar answered Nov 15 '22 11:11

ssube


One more way to do this :

#include <stdio.h>
union int_chars {
    int a;
    char b[4];
};
int main (int argc, char const* argv[])
{
    union int_chars c;
    c.a = 10;
    c.b[0] = 1;
    c.b[1] = 2;
    c.b[2] = 3;
    c.b[3] = 4;
    return 0;
}
like image 34
Rumple Stiltskin Avatar answered Nov 15 '22 11:11

Rumple Stiltskin