问题描述
将二进制字符串转换为有符号整数时遇到问题
I'm having a problem with converting binary strings to signed integers
如果您调用decbin('-40'),则php将输出1111111111111111111111111111111111111111111111111111111111011000
If you call decbin('-40'), php will output 1111111111111111111111111111111111111111111111111111111111011000
但是,如果您调用bindec(decbin('-40')),它将输出1.84467440737E + 19(或类似的东西,显然不是-40),因为它将最高有效位视为另一个数量级而不是作为符号位"-php手册
But if you call bindec(decbin('-40')), it will output 1.84467440737E+19 (or something similar, which is obviously not -40) because it "sees the most significant bit as another order of magnitude rather than as the sign bit" - php manual
有没有一种方法可以将64位二进制二进制字符串(与decbin的输出很相似)转换为有符号整数?
Is there a way to convert a binary 64 bit binary string (much like the one output by decbin) string into a signed integer?
推荐答案
从文档中不能使用 bindec
base_convert
似乎完全忽略了签名.
base_convert
appears to ignore signing altogether.
如果您知道传入的字符串将始终为64位二进制文件,而您不是在32位系统上,则编写自定义函数非常容易.
If you know that your incoming string will always be 64 bit binary and you are not on a 32 bit system, it's quite easy to write a custom function.
- 检查字符串是否为64个字符长.
- 检查最高有效位是否为1.
- 翻转所有位
- 添加1
- 取反
这是我一起敲门的快捷方式.
Here's a quick one I knocked together.
function bindec2($bin)
{
if (strlen($bin) == 64 && $bin[0] == '1') {
for ($i = 0; $i < 64; $i++) {
$bin[$i] = $bin[$i] == '1' ? '0' : '1';
}
return (bindec($bin) + 1) * -1;
}
return bindec($bin);
}
这篇关于PHP:带符号的二进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!