Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

byte array to unsigned int in java

Tags:

java

I'm converting a byte array into int by doing this:

ByteArrayInputStream bais = new ByteArrayInputStream (data);
DataInputStream dis = new DataInputStream (bais);
int j = dis.readInt();

But it returns a signed number where I want an unsigned number, because I want to send that number to the server as an integer during encryption and have to decrypt it at server. if it is a signed number i can do that.

please any 1 help me..........

venu

like image 906
venu Avatar asked Oct 16 '09 06:10

venu


People also ask

Is byte unsigned in Java?

In Java, byte is data type. It is 8-bit signed (+ ive or - ive) values from -128 to 127. The range of unsigned byte is 0 to 255. Note that Java does not provide unsigned byte.

Can we convert byte to int in Java?

The intValue() method of Byte class is a built in method in Java which is used to return the value of this Byte object as int.

How do you make an int unsigned in Java?

For most purposes, all integers in Java are signed. However, you can treat a signed integer as unsigned in one specific case: you can shift right without sign extending by using >>> operator instead of >> .

Why is byte unsigned?

An UnsignedByte is like a Byte , but its values range from 0 to 255 instead of -128 to 127. Most languages have a native unsigned-byte type (e.g., C, C++, C#), but Java doesn't. When manipulating bytes as bit sequences, as we do in the CPU implementation, it is helpful to treat them as unsigned.


1 Answers

An int is always a signed, 32-bit number in Java. However, this only matters if you are doing math with it. If all you care about is the pattern of 0 and 1 bits, simply ignore the sign.

If you do need to do some math, convert it to a long by masking:

long l = j & 0xFFFFFFFFL;

Do all arithmetic with long operands, modulo 0xFFFFFFFFL. When you are done, cast the result back to an int and transmit it.

like image 156
erickson Avatar answered Sep 21 '22 19:09

erickson