Created
January 22, 2013 23:28
-
-
Save bigcalm/4599839 to your computer and use it in GitHub Desktop.
Create a 48bit integer suitable for use with pack() in PHP
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
<?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