【问题标题】:PHP bit/value conversions are not working as expectedPHP 位/值转换未按预期工作
【发布时间】:2013-08-05 17:51:26
【问题描述】:

更新:

对于 googlers,这里是更正的版本:

pastebin.com/tPVWM4MF


我正在尝试创建一个可以像某些默认 php 函数一样解释整数值的类(例如error_reporting(E_ERROR | E_WARNING | E_PARSE);)。出于某种原因,我的一些输出出现了意想不到的结果(请参阅代码)。

有关更多信息,请参阅此页面:Bitwise Operators

如何解决这些意外结果?

代码:

<?php

class bitwise {
    private $xchng = array(
        'bit' => array(
            0000,  0001,
            0010,  0011,
            0100,  0101,
            0110,  0111,
            1000,  1001,
            1010,  1011,
            1100,  1101,
            1110,  1111
        ),
        'val' => array(
            0000 =>  0,  0001 =>  1,
            0010 =>  2,  0011 =>  3,
            0100 =>  4,  0101 =>  5,
            0110 =>  6,  0111 =>  7,
            1000 =>  8,  1001 =>  9,
            1010 => 10,  1011 => 11,
            1100 => 12,  1101 => 13,
            1110 => 14,  1111 => 15
        )
    );
    
    public function create_bit_str($int_input){
        $xchng = $this->xchng['bit'];
        // convert value to bits
        $vals = str_split((string) $int_input,2);
        $values = '';
        foreach ($vals as $val) {
            $val = (int) $val;
            if(isset($xchng[$val])){
                $values .= $xchng[$val];
            }else{
                return FALSE;
            }
        }
        return (int) $values;
    }
    
    public function create_val_str($int_input){
        $xchng = $this->xchng['val'];
        // convert bits to value
    }
}


$bit = new bitwise;
var_dump($bit->create_bit_str(12 & 10)); // output 1000 (expected)
var_dump($bit->create_bit_str(12 | 10)); // output 1110 (expected)
var_dump($bit->create_bit_str(12 ^ 10)); // output 72 (unexpected) should be 0110 or 110

【问题讨论】:

    标签: php oop int bit-manipulation bitwise-operators


    【解决方案1】:

    转储您的“位”数组的内容。你没有得到你认为的价值观。将它们放在引号中,您将获得预期的结果。

    编辑:在你的 vals 数组中做同样的事情。您正在指定十进制数字。换句话说,0010 表示,而不是两个

    【讨论】:

    • 知道了。谢谢!实际上,我在另一台计算机上的原始脚本版本中已经这样做了,我想我忘了重新添加它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 2013-06-19
    • 1970-01-01
    相关资源
    最近更新 更多