0

I am trying to interpret a binary string as an unsigned big endian integer, as her instructions here: http://mimesniff.spec.whatwg.org/#matches-the-signature-for-mp4 (point 4)

I'm not quite sure what I need to do here, but here are my attempts:

// ONE
$box_size   = substr( $sequence, 0, 4 );
$box_size   = pack( 'C*', $box_size[0], $box_size[1], $box_size[2], $box_size[3] );
$box_size   = unpack( 'N*', $box_size );

// TWO
$box_size   = substr( $sequence, 0, 4 );
$box_size   = array_map( 'ord', str_split( $box_size ) );

// THREE
$box_size   = substr( $sequence, 0, 4 );
$box_size   = bindec( $box_size );

// FOUR
$box_size   = substr( $sequence, 0, 4);
$box_size   = (int) $box_size;

I have had no luck, and honestly am not sure what the result should even be.. Does anyone understand this? I think I might be on the right track with pack and unpack.

2
  • Just unpack('N', $string) should do just fine. Commented Apr 18, 2013 at 14:55
  • Wow... That was very easy. The difference between pack and unpack confuses me.. But this seems to have worked a treat. Thanks deceze! Commented Apr 19, 2013 at 2:07

1 Answer 1

4

I'll go ahead and post the comment as an answer then...

To unpack a "compact" bit representation of something into a native type, just use unpack with the right parameters to denote the type of bits you're unpacking. In your case:

$unpacked = unpack('N', $unsignedBigEndianInteger);
$int = $unpacked[1];

This makes PHP read the byte stream assuming it represents an unsigned big endian long and convert it into a PHP native integer.

Remember:

  • pack: "large native type" → squeeze into byte representation
  • unpack: compact byte representation → "large native type"
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, shouldn't it be $unpacked[1]; ? Thanks for that little end note :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.