bitshift?
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...
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.
Note that this assumes little-endianness, which may or may not be correct for your situation.
Quote:Original post by dsageSomething like the following should work:
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...
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.ⁿ,number: 4294717034bytes recv: 4buffer: ╬F√Hnumber: 4294967246bytes recv: 4buffer: 2↑ª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)
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)
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.
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
Popular Topics
Advertisement