PDA

View Full Version : Byte shifting in C



tntcoda
12th November 2008, 23:19
Hi,

I have a QByteArray with 4 bytes in that I want to put in an unsigned int with C, sounds simple but ive spent hours messing around and it wont work :p

Heres an example of what im trying to do, say i have 4 hex bytes 0xFFAD32FF in a QByteArray as data[0] = 0xFF data[1] = 0xAD data[2] = 0x32 data[3] =0xFF and this wants to go into an uint to give the equivalent decimal value of 4289540863.

Im using x86 hardware, so little endian is in use, so I think im correct in saying i have to put the bytes from the array in reverse order? so the unsigned int will look like 0xFF 0x32 0xAD 0xFF in memory is that correct?

Heres my code:


QByteArray input;
// test number
input[0] = 0xFF
input[1] = 0xAD
input[2] = 0x32
input[3] = 0xFF

// Convert to uint
result = input[3];
result = result << 8 | input[2];
result = result << 8 | input[1];
result = result << 8 | input[0];


This gives me a result of 4294967295 instead of 4289540863.

Please can someone point me in the right direction, ive spent a crazy amount of time trying to fix it :p

wysota
12th November 2008, 23:32
I'd try something similar to

memcpy(&result, input.constData(), sizeof(result));
If you really want to, you can swap the byte order before reading from the array or after writing to the destination variable.

tntcoda
12th November 2008, 23:40
Thanks very much, that seems to work correctly if i reverse the order of the byte array before calling memcpy().

wysota
14th November 2008, 22:40
You can also use things such as ntohl() and htonl() to do the conversion. You'd get platform independency for free.