Skip to content

Instantly share code, notes, and snippets.

@bigcalm
Created January 22, 2013 23:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bigcalm/4599839 to your computer and use it in GitHub Desktop.
Save bigcalm/4599839 to your computer and use it in GitHub Desktop.
Create a 48bit integer suitable for use with pack() in PHP
<?php
$topUp = 100;
list($integerPart1, $integerPart2) = convertTo48bit($topUp);
$packedInteger = pack("vV", $integerPart1, $integerPart2);
echo json_encode($packedInteger) . "\n";
function convertTo48bit($integer)
{
// convert to binary and pad to 48 bits
$bin48bit = sprintf("%048b", $integer);
// split into two and four byte chunks
$twoBytes = substr($bin48bit, 0, 16);
$fourBytes = substr($bin48bit, 16, 48);
// convert each back to decimal
$unsignedShort = bindec($twoBytes);
$unsignedInteger = bindec($fourBytes);
// return for use
return array($unsignedShort, $unsignedInteger);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment