PHP Binary to Hex with leading zeros

后端 未结 3 1740
無奈伤痛
無奈伤痛 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));
    
    0 讨论(0)
  • 2021-01-23 05:29

    Use str_pad() for that:

    // maximum number of chars is maximum number of words 
    // an integer consumes on your system
    $maxchars = PHP_INT_SIZE * 2; 
    $hex = str_pad($hex, $maxchars, "0", STR_PAD_LEFT);
    
    0 讨论(0)
  • 2021-01-23 05:32

    You can prepend the requisite number of leading zeroes with something such as:

    $hex = str_repeat("0", floor(strspn($binary, "0") / 4)).$hex;
    

    What does this do?

    1. It finds out how many leading zeroes your binary string has with strspn.
    2. It translates this to the number of leading zeroes you need on the hex representation. Whole groups of 4 leading zero bits need to be translated to one zero hex digit; any leftover zero bits are already encoded in the first nonzero hex digit of the output, so we use floor to cast them out.
    3. It prepends that many zeroes to the result using str_repeat.

    Note that if the number of input bits is not a multiple of 4 this might result in one less zero hex digit than expected. If that is a possibility you will need to adjust accordingly.

    0 讨论(0)
提交回复
热议问题