PHP Binary to Hex with leading zeros

后端 未结 3 1765
無奈伤痛
無奈伤痛 2021-01-23 04:58

I have the follow code:


Which works fine, and I get a valu

3条回答
  •  长发绾君心
    2021-01-23 05:27

    You can do it very easily with sprintf:

    // Get $hex as 3 hex digits with leading zeros if required. 
    $hex = sprintf('%03x', bindec($binary));
    
    // Get $hex as 4 hex digits with leading zeros if required. 
    $hex = sprintf('%04x', bindec($binary));
    

    To handle a variable number of bits in $binary:

      $fmt = '%0' . ((strlen($binary) + 3) >> 2) . 'x';
      $hex = sprintf($fmt, bindec($binary));
    

提交回复
热议问题