bitshift?

Started by
6 comments, last by bakery2k1 17 years, 12 months ago
I have 4 bytes I recieved from a socket. I need to turn the 4 bytes into an unsigned int. Can i do this with bitshift? and how? Thanks...
Advertisement
unsigned int data = (unsigned int)byte1 | ((unsigned int)byte2 << 8) | ((unsigned int)byte3 << 16) | ((unsigned int)byte4 << 24);

Note that this assumes little-endianness, which may or may not be correct for your situation.
Quote:Original post by dsage
I have 4 bytes I recieved from a socket. I need to turn the 4 bytes into an unsigned int. Can i do this with bitshift? and how? Thanks...
Something like the following should work:
unsigned int result =    (unsigned int)byte[0] << 0 |    (unsigned int)byte[1] << 8 |    (unsigned int)byte[2] << 16 |    (unsigned int)byte[3] << 24;
You may have to reverse the index order depending on endian-ness.

[Edit: beaten.]
I'm getting some strange output...

byteCount = recv(client, buffer, 4, 0);        std::cout << "bytes recv: " << byteCount << std::endl;        std::cout << "buffer: " << buffer << std::endl;        number = ((unsigned int)buffer[0] << 0) | ((unsigned int)buffer[1] << 8) | ((unsigned int)buffer[2] << 16) | ((unsigned int)buffer[3] << 24);        std::cout << "number: " << number << std::endl;[\source]output: bytes recv: 4buffer: ±äòmnumber: 4294967281bytes recv: 4buffer: j.&#8319;,number: 4294717034bytes recv: 4buffer: &#9580;F&#8730;Hnumber: 4294967246bytes recv: 4buffer: 2&#8593;ªAnumber: 4289075250
unsigned int n = * (unsigned int *) buffer;

This assumes "buffer" is an array of bytes. Please ensure that you actually have sizeof(unsigned int) bytes before doing this (or any of the other solutions).

Depending on the protocol that you're speaking you may also need the following to get the bytes in the right order:

n = ntohl(n)
-Mike
buffer is an array of chars
Quote:Original post by Anon Mike
unsigned int n = * (unsigned int *) buffer;


However, this is not possible on CPUs where unaligned access causes a crash.
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!
It seems your input data is big-endian. Try switching the order in which the bytes are processed:

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

This topic is closed to new replies.

Advertisement