Forked from paulononaka/JavaIntToLittleEndianUnsigned
Last active
October 25, 2021 03:00
-
-
Save cicorias/3f8f1e88f46192b925fd7eca4a832209 to your computer and use it in GitHub Desktop.
Convert a Int (in Java, big endian signed) to LittleEndian unsigned
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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