C++ Convert array elemets

Started by
13 comments, last by noe 15 years, 4 months ago
Quote:Original post by REspawn
I tried the bit shifts with the end result always being 0.

unsigned long result = rawHeader[4] << 24 + rawHeader[5] << 16 + rawHeader[6] << 8 + rawHeader[7];

this should now hold the number 3, any ideas what I'm doing wrong?
You are shifting 8-bit numbers: what happens when you shift an 8-bit number 24-bits to the left? You get 0, since all existing bits are shifted out, and 0 bits are brought in from the right.

You also appear to be doing a byte-order conversion at the same time.

Try something like this:
unsigned long result = 0;for (int i = 4; i > 0; i++) {	result <<= 8;	result += rawHeader[i-1];}

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

Advertisement
Quote:Original post by swiftcoder
You are shifting 8-bit numbers

No. The general rule is that everything smaller than an int is promoted to an int before the actual operation.
int main(void){    unsigned char b = 123;    printf("%d\n%d\n", sizeof b, sizeof (b+b));    return 0;}

This prints 1 for sizeof b and 4 for sizeof (b+b).
Quote:Original post by REspawn
unsigned long result = rawHeader[4] << 24 + rawHeader[5] << 16 + rawHeader[6] << 8 + rawHeader[7];

+ has higher precedence than <<. Use | instead of +, that should work.

unsigned long result = rawHeader[4] << 24 | rawHeader[5] << 16 | rawHeader[6] << 8 | rawHeader[7];
Quote:Original post by DevFred
Quote:Original post by swiftcoder
You are shifting 8-bit numbers

No. The general rule is that everything smaller than an int is promoted to an int before the actual operation.
int main(void){    unsigned char b = 123;    printf("%d\n%d\n", sizeof b, sizeof (b+b));    return 0;}

This prints 1 for sizeof b and 4 for sizeof (b+b).
Ah shoot, forgot about integer promotion - thanks for correcting.

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

Yes, but the most important part is that due to operator precedence rules, the forumla with the + operator is evaluated as follows:
unsigned long result = rawHeader[4] << (24 + rawHeader[5]) << (16 + rawHeader[6]) << (8 + rawHeader[7]);

Which just shifts the bits from rawHeader[4] waaaaay too far to the left (at least 24 + 16 + 8 = 48 bits).
the simplest way (just reinterpreting memory block) would be:

int* intBegin = (Int*) uint8Array;
int* intEnd = intBegin + sizeOfUint8Array / sizeof(int);

std::copy(intBegin, intEnd, intArray);

[Edited by - noe on December 4, 2008 10:23:39 AM]

This topic is closed to new replies.

Advertisement