Skip to content

NEW dec2bin() and bin2dec() functions #16667

@lunter2

Description

@lunter2

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions