Last active
January 3, 2016 03:39
-
-
Save enrobsop/8403667 to your computer and use it in GitHub Desktop.
Groovy equivalent of Perl/ PHP pack("N", int) function.
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
// 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