PHP:带符号的二进制字符串 [英] PHP: Signed Binary Strings

查看:52
本文介绍了PHP:带符号的二进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将二进制字符串转换为有符号整数时遇到问题

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

bindec()将所有binary_string值解释为无符号整数.这是因为bindec()将最高有效位视为另一个数量级,而不是符号位.

bindec() interprets all binary_string values as unsigned integers. This is because bindec() sees the most significant bit as another order of magnitude rather than as the sign bit.

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:带符号的二进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆