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
1 day 20 hours ago
1 day 20 hours ago
4 days 20 hours ago
4 days 22 hours ago
6 days 15 hours ago
6 days 15 hours ago
1 week 1 day ago
1 week 3 days ago
2 weeks 4 days ago
2 weeks 4 days ago