-
Notifications
You must be signed in to change notification settings - Fork 8k
Closed
Labels
Description
Description
Since the pack() function does not support variable (minimum) length encodings, I would like to propose two useful functions for direct implementation in PHP.
Currently, you have to use a combination of:
- dechex() -> hex2bin() with odd/even length check
- bin2hex() -> hexdec()
which is not optimal for performance.
<?
function dec2bin($dec){
$hex=dechex($dec);
if(strlen($hex)%2===1){ // is an odd length
$hex='0'.$hex;
}
$bin=hex2bin($hex); // $hex must have an even length
return $bin;
}
function bin2dec($bin){
$hex=bin2hex($bin);
$dec=hexdec($hex);
return $dec;
}
$dec=random_int(0,1000);
$bin=dec2bin($dec);
$new_dec=bin2dec($bin);
print($new_dec===$dec?'OK':'ERROR'); // test
?>