Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Byte[] as unsigned short Java

Tags:

java

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!!

like image 418
Ameen Avatar asked Oct 28 '11 17:10

Ameen


People also ask

Can we convert byte to short in Java?

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.

Is byte in Java unsigned?

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).

How do you convert two bytes to short?

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.

Can we convert byte array to file in Java?

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.


2 Answers

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.

like image 82
Frank Avatar answered Sep 18 '22 15:09

Frank


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

like image 41
Mechkov Avatar answered Sep 21 '22 15:09

Mechkov