带有前导零的PHP二进制到十六进制 [英] PHP Binary to Hex with leading zeros
问题描述
我有以下代码:
I have the follow code:
<?
$binary = "110000000000";
$hex = dechex(bindec($binary));
echo $hex;
?>
哪些工作正常,我得到c00的值。
Which works fine, and I get a value of c00.
然而,当我尝试转换000000010000时,我得到值10。我真正想要的是所有的前导零,所以我可以得到010作为最终结果。
However, when I try to convert 000000010000 I get the value "10". What I actually want are all the leading zeros, so I can get "010" as the final result.
我该怎么做?
编辑:我应该指出,二进制数的长度可能会有所不同。所以$ binary可能是00001000,这会导致它为08。
I should point out, the length of the binary number can vary. So $binary might be 00001000 which would result it 08.
推荐答案
您可以在前面加上必要数量的前导零, :
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?
- 它发现你的二进制字符串有多少个前导零,它们是
strspn
。 - 它将它转换为数字你需要十六进制表示的前导零。整组的4个前导零位需要转换为一个零十六进制数字;任何剩余的零位已经被编码在输出的第一个非零十六进制数字中,所以我们使用
floor
将它们排除。 - 它使用
str_repeat
。
- It finds out how many leading zeroes your binary string has with
strspn
. - 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. - It prepends that many zeroes to the result using
str_repeat
.
注意,如果结果为零输入位的数量不是4的倍数,这可能导致一个比预期的零十六进制数字更少。如果这是可能的,您需要相应调整。
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.
这篇关于带有前导零的PHP二进制到十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!