I need to read a byte array of 16 bits as unsigned short number, and Java doesn't support unsigned short type.
So how can i do it?? Please help!!
The shortValue() method of Byte class is a built in method in Java which is used to return the value of this Byte object as short.
In Java, byte is an 8-bit signed (positive and negative) data type, values from -128 (-2^7) to 127 (2^7-1) . For unsigned byte , the allowed values are from 0 to 255 . Java doesn't have unsigned bytes (0 to 255).
put(secondByte); short shortVal = bb. getShort(0); And vice versa, you can put a short, then pull out bytes. By the way, bitwise operations automatically promote the operands to at least the width of an int.
Convert byte[] array to File using Java In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file.
Assuming you have it available as binary data from a non-Java source that you must read and work with the values in Java:
Read it as a (signed) short
, and then convert it to int
as follows:
int intVal = shortVal >= 0 ? shortVal : 0x10000 + shortVal
You cannot represent all values of an unsigned short in a short, but in an int, you can.
I don't know if you HAVE to use an unsigned short, but in case you don't, you can always use a char to hold an unsigned short. Take a look at this article that gives a simple overview
http://darksleep.com/player/JavaAndUnsignedTypes.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With