I have this loop:
$encoded = '';
while ($number) {
$encoded = chr($number & 0xFF) . $encoded;
$number = $number >> 8;
}
return $encoded;
and I was wondering whether there's an equivalent pack
or unpack
for it.
I have this loop:
$encoded = '';
while ($number) {
$encoded = chr($number & 0xFF) . $encoded;
$number = $number >> 8;
}
return $encoded;
and I was wondering whether there's an equivalent pack
or unpack
for it.
You're encoding this as a big-endian representation (meaning most significant byte first), but with a variable width.
So to get the bytes:
pack("N", $number)
You can also use 64 bit with J
.
But you also need to trim off leading null bytes (for variable width):
ltrim(pack("N", $number), chr(0))