Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cicorias/3f8f1e88f46192b925fd7eca4a832209 to your computer and use it in GitHub Desktop.
Save cicorias/3f8f1e88f46192b925fd7eca4a832209 to your computer and use it in GitHub Desktop.
Convert a Int (in Java, big endian signed) to LittleEndian unsigned
private static byte[] intToLittleEndian(long numero) {
ByteBuffer bb = ByteBuffer.allocate(4);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.putInt((int) numero);
return bb.array();
}
// OR ...
private static byte[] intToLittleEndian(long numero) {
byte[] b = new byte[4];
b[0] = (byte) (numero & 0xFF);
b[1] = (byte) ((numero >> 8) & 0xFF);
b[2] = (byte) ((numero >> 16) & 0xFF);
b[3] = (byte) ((numero >> 24) & 0xFF);
return b;
}
int htonl(int value) {
return ByteBuffer.allocate(4).putInt(value)
.order(ByteOrder.nativeOrder()).getInt(0);
}
int htonl(int value) {
if (ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN) {
return value;
}
return Integer.reverseBytes(value);
}
stream.write(msg.length() % 256);
stream.write((msg.length() / 256) % 256);
stream.write((msg.length() / (256 * 256)) % 256);
stream.write((msg.length() / (256 * 256 * 256)) % 256);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment