PHP Binary to Hex with leading zeros

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

I have the follow code:


Which works fine, and I get a valu

3条回答
  •  暗喜
    暗喜 (楼主)
    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.

提交回复
热议问题