I would like to store 4 char (4 bytes) into an unsigned int.
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)
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;
}
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