更新:
对于 googlers,这里是更正的版本:
我正在尝试创建一个可以像某些默认 php 函数一样解释整数值的类(例如error_reporting(E_ERROR | E_WARNING | E_PARSE);
)。出于某种原因,我的一些输出有意想不到的结果(见代码)。
有关更多信息,请参阅此页面:按位运算符
我该如何解决这些意外结果?
编码:
<?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