Java Byte Array Conversion

This is a small class to convert a byte array to short and int, faster than with a ByteBuffer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class Convert {
// byte to "unsigned int"
// this is needed because there is are no unsigned types in java
public static int BToUI(byte b) {
return ((int) b) & 0XFF;
}
// byte to short
public static short BAToS(byte b[]) {
return BAToS(b, 0);
}
// byte to short with an offset in the byte array
public static short BAToS(byte b[], int offset) {
return (short) (((b[offset + 1] & 0xFF) << 8) | (b[offset] & 0xFF));
}
// byte array to an integer
public static int BAToI(byte b[]) {
return BAToI(b, 0);
}
// byte array to an integer with an offset
public static int BAToI(byte b[], int offset) {
return ((b[offset + 3] & 0xFF) << 24) |
((b[offset + 2] & 0xFF) << 16) |
((b[offset + 1] & 0xFF) << 8) |
(b[offset] & 0xFF);
}
// byte array to float
public static float BAToF(byte b[]) {
return Float.intBitsToFloat(BAToI(b));
}
}