This question is for the developers/everyone who knows about binary conversion on Lockergnome.net
I am currently having trouble with a custom network library which I plan to use for a lower data usage and therefore faster data transmission. It has to work on both C# and Java so therefore I will not be using any build in classes like BitConverter(C#).
My problem basically is that my numbers aren't being converted the way they should. When I pass a short with an value of 500 it returns 2 bytes of the values 244 and 0. This represents the short 244 not 500. With a value of 512 it returns 2 zero's
My current code in C#
short num = 500; byte offset = 0xff; byte b1 = (byte)(offset & num); // 244 byte b2 = (byte)((offset & num) >> 8); // 0, should be 1 since (1 * 256) + 244 = 500 //short has been converted to bytes (the wrong way) short s = b1; // 244 s = (short)(s << b2); // 244 (didn't add anything for the 0 byte which is correct)
It doesn't matter which type of endian it uses as long as it transmits and receives the right data.
What am I doing wrong?
asked Feb 19 '11 at 19:01
A right shift by 8 is equal to a division by 256, so (0xff & num) >> 8 is always 0. In fact, 0xff >> 8 is always 0. What makes you think otherwise?
... or using division instead:
answered Jun 18 '11 at 10:55