Skip to content

Instantly share code, notes, and snippets.

@enrobsop
Last active August 19, 2021 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save enrobsop/8403717 to your computer and use it in GitHub Desktop.
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)
// 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
}
}
@ptahchiev
Copy link

This doesn't seem to be valid Java (def and as keywords are not java)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment