Wednesday, March 23, 2005

How do I read an unsigned byte in Java?


Bytes in Java are signed values from -128 to 127. This is a bit of a problem if you need to work with unsigned bytes ranging from 0 to 255, inclusive. There's an explanation why bytes in Java are signed, but why is there no methods for handling unsigned bytes? Anyway, read on and I will explain how to write methods handling unsigned bytes.


public class UnsignedByte {    
    public static void main(String[] args) {
        byte b = -1; // signedByte = -1, unsignedByte = 255
        int i = b & 0xFF; // unsignedInt = signedByte & 0xFF;
        b = (byte) i; // signedByte = (byte) unsignedInt;


[user]$ java UnsignedByte


In order to do math operations on unsigned bytes in Java, you should first convert them to ints. This works because:

-1        = 11111111111111111111111111111111
0xFF      = 00000000000000000000000011111111
-1 & 0xFF = 00000000000000000000000011111111 = 255


If you are going to use this code a lot, it would be better to rewrite the code as methods (NetSpy 2003):

public final class UnsignedByte {
    public static void main(String[] args) {
        byte b = -1;
        int i = 255;
    public static int unsigned(byte b) {
        return b & 0xFF;
    public static byte signed(int i) {
        return (byte) i;
[user]$ java UnsignedByte


Author NetSpy
Year 2003
Title NetSpy Version 2.0
Place Holland, MI
Publisher Hope College Department of Computer Science
Retrieved Wednesday, April 13, 2005


TH said...

Thanks a lot, this was very useful for me! :)))

Gaute Lykkenborg said...

That's great! But how was it useful? What kind of problem were you working on?

Alfonso Garcia said...

Thanks! Very clear and useful information... Keep the good work!

Alfonso Garcia said...

In case you ask How was it useful for me... :)
I'm implementing the XModem protocol for transfering files between computers via Bluetooth (using only Serial Profile Protocol).
I was having problems handling and sending the bytes with the right value, as well as having problems when calculating the CRC.


Gaute Lykkenborg said...

Alfonso, I think that knowing why some piece of code is useful, and what you can use it for, is extremely important. Otherwise the code easily becomes just some clever academic exercise with no purpose in real life. So, thank you for your helpful and constructive feedback! Great!

Free SMS said...

Very good.

mpp said...

Thanks a lot!!!

U.A.S said...

Thank you so much!!
I needed to pass from byte[] to a String (in representing IPs) and I got a -64 instead of a 192.

This is a brilliant solution which helped me a lot!! Thanks!!