I\'m converting a byte array into int
by doing this:
ByteArrayInputStream bais = new ByteArrayInputStream (data);
DataInputStream dis = new Data
Java's primitive integer types (i.e. byte, short, int and long) are all signed. But you can work around this.
To do (say) 32 bit unsigned arithmetic, just do the arithmetic pretending that 'int' is unsigned. For example, 2**31 - 1
is the largest (signed) int
value. If you add one to it you will get -2**31
. But that bit pattern is the same as +2**31
if you think of the int
as being unsigned. This also works for subtraction and multiplication. (I'm not sure about division and remainder, but the chances are that doesn't matter for you).
Comparing unsigned 32 bit values is a bit more tricky. For example, -1
is less that +1
, but if you interpret -1
as an unsigned value you get +2**32 - 1
which should be greater than '+1'. You can compensate by translating the inequality (I'll leave it to the reader to figure it out) or by casting the int
values to long
, masking them with 0xffffffffL
and comparing them as longs; e.g.
int u1 = ...
int u2 = ...
if ((((long) u1) & 0xffffffff) < (((long) u2) & 0xffffffff) {
// u1 represents a smaller unsigned value than u2
}
Converting 32 bit unsigned integers to Strings is easiest done using longs; e.g.
String str = Long.toString(((long) u1) & 0xffffffffL);
Now I'll freely admit that using int
to represent 32 bit unsigned values is tricky, and potentially error prone. A cleaner solution would be to use long
throughout, or if your application needs 64 bit unsigned values to use BigInteger
.
UPDATE - it looks Java 8 will have support (in the form of library methods) for treating int
and long
as unsigned types - see "Unsigned Integer Arithmetic API now in JDK 8" by Joseph Darcy @ Oracle.
Each cell in the array is treated as unsigned int:
private int unsignedIntFromByteArray(byte[] bytes) {
int res = 0;
if (bytes == null)
return res;
for (int i = 0; i < bytes.length; i++) {
res = (res *10) + ((bytes[i] & 0xff));
}
return res;
}
Java does not have unsigned int, so you'll have to manually invert the bits to get an unsigned value if you absolutely need to have one.
Got this from Google.
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.