Monday, 16 August 2010

Java unsigned int to signed byte and back again

In the last month or so I've been spending a lot of time playing with protocols in Java. Having previously done this kind of work in either .NET or C++ I had become accustomed to having unsigned data types available to me. So coming to Java I was a little shocked that they were missing. This seems somewhat accepted in the Java community so I am, of course, going with the flow.

Despite Java having some very useful classes like the java.io ByteArrayInputStream and ByteArrayOutputStream I found very little information out there on what exactly happens when you want to read or write unsigned byte values. So I wrote a little bit of test code to prove that my understanding was correct:


int in, out;
byte b;

in = 0;
b = (byte)in;
out = b & 0xff;
System.out.println("in=" + in + ", b=" + b + ", out=" + out);


in = 127;
b = (byte)in;
out = b & 0xff;
System.out.println("in=" + in + ", b=" + b + ", out=" + out);


in = 128;
b = (byte)in;
out = b & 0xff;
System.out.println("in=" + in + ", b=" + b + ", out=" + out);


in = 255;
b = (byte)in;
out = b & 0xff;
System.out.println("in=" + in + ", b=" + b + ", out=" + out);

Which produces the following output to the Console:


in=0, b=0, out=0
in=127, b=127, out=127
in=128, b=-128, out=128
in=255, b=-1, out=255

Hopefully this might be of use to somebody. It certainly made me feel more at ease 'flinging them bytes about'!

0 comments:

Post a Comment