chx
chx

Reputation: 11790

Is there a pack/unpack version of this?

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.

Upvotes: 2

Views: 107

Answers (1)

ircmaxell
ircmaxell

Reputation: 165271

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))

Upvotes: 3

Related Questions