There're a lot of ways to do this right and a lot of ways to do it wrong.

Here's one method that I've found to be both correct (ie. for all possible integer values the following is true:
value == byteArrayToInt(intToByteArray(value))
) and efficient.
Both functions work with big-endian representations of 4-byte integer values.
public static final byte[] intToByteArray(int value) {
return new byte[] {
(byte) (value >>> 24),
(byte) (value >>> 16),
(byte) (value >>> 8),
(byte) value
};
}
public static final int byteArrayToInt(byte[] b) {
int value = 0;
if (b != null) {
if (b.length > 0) {
value += b[0] << 24;
if (b.length > 1) {
value += (b[1] & 0xFF) << 16;
if (b.length > 2) {
value += (b[2] & 0xFF) << 8;
if (b.length > 3) {
value += b[3] & 0xFF;
}
}
}
}
}
return value;
}
Using the above examples you can easily create functions that do the same conversion for
long
values (ie. longToByteArray() and byteArrayToLong()).
Recent comments
2 years 34 weeks ago
4 years 3 weeks ago
4 years 3 weeks ago
4 years 5 weeks ago
4 years 6 weeks ago
4 years 13 weeks ago
4 years 13 weeks ago
4 years 13 weeks ago
4 years 13 weeks ago
4 years 14 weeks ago