如何将整数转换为它的位表示?
例如,数字9的位表示为:10011
例如,要将位序列转换为它的int表示,您可以这样做:
$bits_sq = array(1,0,0,1,1);
function convert_bits_to_int($bits_sq){
$sum = 0;
for($i=0; $i < count($bits_sq); $i++){
$sum = $sum + $bits_sq[$i] * pow(-2, $i);
}
print $sum; // equals to 9
}
但我想要反过来。
编辑:不要误解二进制的比特,这不是重复,而是在上面有回答
答案 0 :(得分:5)
答案 1 :(得分:2)
我的php是生锈的,但是如果你想反过来这个例子
$bits_sq = array(1,0,0,1,1);
function convert_bits_to_int($bits_sq){
$sum = 0;
for($i=0; $i < count($bits_sq); $i++){
$sum = $sum + $bits_sq[$i] * pow(-2, $i);
}
print $sum; // equals to 9
}
然后我想你想要这样的东西:
$bits_sq = convert_int_to_bits ($iValue);
function convert_int_to_bits ($iValue) {
$bits = array(); // initialize the array
do {
$bits[] = ($iValue & 1);
$iValue >>= 1; // shift the bit off so that we go to the next one
} while ($iValue); // continue as long as there are still some bits.
// we have the bits in reverse order so lets reverse it.
return array_reverse($bits);
}