Last active
August 19, 2021 05:31
-
-
Save enrobsop/8403717 to your computer and use it in GitHub Desktop.
Java equivalent of Perl/ PHP pack("N", int) function. (Based on Groovy version at https://gist.github.com/enrobsop/8403667)
This file contains 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
// Java equivalent of: | |
// PHP: pack("N", 123) and unpack("N", str) | |
// Perl: pack("N", 123) and unpack("N", str) | |
static String packN(int value) { | |
byte[] bytes = ByteBuffer.allocate(4).putInt(value).array(); | |
bytes = toPositiveByteArray(bytes); | |
return String.valueOf((char[]) bytes); | |
} | |
static int unpackN(String value) { | |
byte[] bytes = (value.chars as int[]) as byte[]; | |
ByteBuffer buf = ByteBuffer.allocate(4); | |
buf.order(ByteOrder.BIG_ENDIAN); | |
buf.put(bytes); | |
buf.flip(); | |
return buf.getInt(); | |
} | |
// converts a byte[] like [0,0,19,-2] to [0,0,19,254] | |
static def toPositiveByteArray(bytes) { | |
bytes.collect { | |
it < 0 ? 256 + it : it | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This doesn't seem to be valid Java (def and as keywords are not java)