tags:

views:

57

answers:

1

So I byte shift a integer into 4 bytes of data.

img[4] = (imagewidth >> 24) & 0xFF;
img[5] = (imagewidth >> 16) & 0xFF;
img[6] = (imagewidth >> 8) & 0xFF;
img[7] = imagewidth & 0xFF;

img[8] = (imageheight >> 24) & 0xFF;
img[9] = (imageheight >> 16) & 0xFF;
img[10] = (imageheight >> 8) & 0xFF;
img[11] = imageheight & 0xFF;

Now how would I go about shifting it back to an integer. so img[8] - img[11] back to a single int or img[4] - img[7] back to a single int

+6  A: 
imagewidth = img[4] << 24 | img[5] << 16 | img[6] << 8 | img[7];
imageheight = img[8] << 24 | img[9] << 16 | img[10] << 8 | img[11];
KennyTM
Hopefully `img[]` was declared `unsigned char` so that you don't get sign extension when the individual bytes are promoted to `int` before each shift. Writing it as `img[4] << 24U | ...` would be a way to make intent clearer to the compiler and protect against that mistake by requiring that each subexpression promote to `unsigned int` instead of `int`.
RBerteig
@RBerteig: I think the right operand on a shift has no influence on the result type, so this wouldn't help. And for negative values left shift is simply undefined behavior.
Jens Gustedt
@Jens, You are right, the LHS of a shift controls the type of the result, not the RHS. And left shifts of signed types are fraught with undefined behaviors. That strengthens my first point. The byte array has to be declared as `unsigned char` or the arithmetic will invoke undefined behavior.
RBerteig