dowdw44426 2014-01-24 18:51
浏览 21
已采纳

右移不按预期工作

I need to do some bit twiddling to pull out some data I'm getting from another source.

The data I've got looks like this in binary:

01100011 00000000 00000000 00000000

Which is the little-endian encoding of the decimal number 99.

I want to mask (bitwise-and) it with this value:

01000000 00000000 00000000 00000000

And then shift all the way to the right (30 places).

When I try right-shifting it, however, I get:

00000000 00000000 00000000 00110000

And I can't figure out why.

Here's the code:

function binrep($bin,$len=32) {
    return implode(' ',str_split(str_pad(decbin(hexdec(bin2hex($bin))),$len,'0',STR_PAD_LEFT),8));
}


function mask($data,$pos,$len=1,$size=32) {
    $bits = (1<<$len)-1;
    $shift = $size - $pos - $len;
    $mask = pack('N',$bits << $shift);
    echo binrep($data)."
".binrep($mask)."
".binrep(($data&$mask)>>$shift);
    return ($data & $mask) >> $shift;
}

mask(pack('V',99),1);

Where is that value coming from? Why isn't the result

00000000 00000000 00000000 00000001

?

  • 写回答

2条回答 默认 最新

  • duanshan3427 2014-01-24 19:47
    关注

    This is a type mismatch. Since ($data & $mask) evaluates to a string, php is implicitly changing the type of $shift to a string to do the operation. And as per the php documentation, this means the >> operator is using ascii values to do the calculation. I added this function to your code:

    function decrep($bin)
    {
    return hexdec(bin2hex($bin));
    }
    

    then did the shift to the right using this function binrep(pack('N',((decrep($data) & decrep($mask)) >> $shift))) and this gives the correct result.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?