dongliang1873 2016-06-22 14:13
浏览 59

清除最高有效位

I have a file containing two bytes, in Big Endian order, hexdump gives me:

81 50

which is 1000 0001 0101 0000 in binary. However, I want the most significant bit to be a flag, so in golang I have to load the file content, clear the most significant bit, and only then read the value.

So:

valueBuf := make([]byte, 2)
_, err := f.Read(valueBuf) // now printing valueBuf gives me [129 80] in decimal
value := int16(binary.BigEndian.Uint16(valueBuf[0:2])) // now value is -32432

Ok, I have tried to use something like:

func clearBit(n int16, pos uint) int16 {
    mask := ^(1 << pos)
    n &= mask
    return n
}

But it apparently doesn't work as expected. The output value should be 336 in decimal, as normal int, and I cannot get it. How should I do this?

  • 写回答

1条回答 默认 最新

  • dongzan9069 2016-06-22 14:21
    关注

    for n &= mask to work, n and mask have to be matching types. So you should write

    mask := int16(^(1 << pos))
    

    then, value = clearBit(value, 15) works fine.

    Or, since constants are untyped, you can eliminate mask, and also eliminate the assignment to n since it's just returned on the following line, and shorten clearBit to

    func clearBit(n int16, pos uint) int16 {
        return n & ^(1 << pos)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM