Breaking it up into 2 shorts won't make it any more efficient. You'll also need to enclose your shifts in brackets - you can't say something like this... int a = b << 2 | 0xff; ...because the bitwise operations are off the same order-of-operation level and the compiler won't know which to perform first. It should be offe of these: int a = (b << 2) | 0xff; int a = b << (2 | 0xff);
I would do it like this since its easy to understand and just as efficient (again, not sure if the casts are necessary - can someone correct me?): combo = ((long)b1 << 24) | ((long)b2 << 16) | ((long)b3 << 8) | b4;
The casts don't really need to be unsigned since you're offly do shifts and ORs and they work the same for signed and unsigned data.
As for your getting the bits out, you're changing the value of combo when you don't need to. Its always better to avoid writing when you don't have to. Do it like this: b1 = (char)combo >> 24; b2 = (char)combo >> 16; b3 = (char)combo >> 8; b4 = (char)combo;
The shifts will move the byte you want to the lowest 8 bits. When the cast happens, any higher bits will be forgotten.
I notice you're using a type called BYTE, presumably for portability reasons. However, at the same time you're assuming that longs are 32 bits and shorts are 16 bits. You should go either one way or the other. Either use special types like BYTE, WORD, and DWORD, or use the built in unsigned char, unsigned short, and unsigned long (or int).
[edited by - dcosborn on March 1, 2004 7:24:58 PM]
> ...because the bitwise operations are on the same order-of-operation level and the compiler won''t know which to perform first. nope, shift has higher priority than or.