Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Convert byte

Status
Not open for further replies.

specv

Programmer
Aug 8, 2001
42
CA
Hi
I have a program that use DatagramPacket. I receive message from the server and I want to interpretes the result in a byte array. But the problem is that the byte is signed.
ex : I have -61 in byteArray[16] but the true result is 195.
How can I convert signed byte to unsigned?
Thanks
Phil
 
see your post "ArrayLists" - thread269-649629
 
I think the only unsigned numbers in java is char. Everything else is signed(correct me if i'm wrong).
The left-most bit is always used for sign(+/- represented
by 0/1 respectively).

This post a while back might give you some ideas.

thread269-580099

~za~
You can't bring back a dead thread!
 
specv,

Depends what you want to do with it. If you just want to calculate with it you can use the method "uByteToInt()" from the following code.
You could also make a special class "uByte" for example and implement all the functionality you need in there. Then you could make an array of "uByte" (and pass your byte array as parm in the constructor) ...
Code:
public class UnsignedByte {

  public UnsignedByte() {
  }

  public static void main(String[] args) {
    UnsignedByte unsignedByte = new UnsignedByte();
    unsignedByte.doIt();
  }

  public void doIt() {
    byte b = -61;
    System.out.println("Byte = " + b);
    System.out.println("Unsigned byte = " + uByteToInt(b));
  }

  public int uByteToInt (byte b) {
    return ((int) b) & 0xFF;
  }

}
==============================
The output :
==============================
Byte = -61
Unsigned byte = 195
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top