Skip to content

Instantly share code, notes, and snippets.

@enrobsop
Last active January 3, 2016 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enrobsop/8403667 to your computer and use it in GitHub Desktop.
Save enrobsop/8403667 to your computer and use it in GitHub Desktop.
Groovy equivalent of Perl/ PHP pack("N", int) function.
// Groovy equivalent of:
// PHP: pack("N", 123) and unpack("N", str)
// Perl: pack("N", 123) and unpack("N", str)
static String packN(int value) {
def bytes = ByteBuffer.allocate(4).putInt(value).array()
bytes = toPositiveByteArray(bytes)
(bytes as char[]).toString()
}
static int unpackN(String value) {
def bytes = (value.chars as int[]) as byte[]
ByteBuffer buf = ByteBuffer.allocate(4)
buf.order(ByteOrder.BIG_ENDIAN)
buf.put(bytes)
buf.flip()
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