douyujun0152 2018-06-01 17:13
浏览 167
已采纳

如何在Go中使用位移运算符将两个`uint8`连接成`uint16`?

I am trying to develop a toy CPU architecture in Go to learn and familiarise myself with the language, something I had done before in C. However, one part of the learning process has surprised me, and that is bit manipulation. In particular, I am struggling with implementing the concatenation of two 8 bit values into a 16-bit value. I have translated this general purpose C code I wrote:

uint16_t connect(uint8_t a, uint8_t b)
{
    return (uint16_t) a | (uint16_t) b << 8;
}

Into this Go code:

func DereferenceWord(addr uint32) uint16 {
    return uint16(memoryPointer[addr]) | uint16(memoryPointer[addr + 1] << 8)
}

To me at least, the code seems correct. However, when tested with 0xff, 0xff and 0x0000 (address in my VM pointing to value 0xffff), the Go code outputs 0xff only (while the C code outputs the correct 0xffff). Why could this be?

CONTEXT: function that sets a word in the VM's memory. Tested and working.

func SetWord(addr uint32, data uint16) {
    initial := 0
    for i := 0; i < 2; i++ {
        memoryPointer[addr + uint32(i)] = uint8((data >> uint32(initial)) & 0xff)
        initial += 8
    }
}
  • 写回答

1条回答 默认 最新

  • drqrdkfue521903877 2018-06-01 17:24
    关注

    memoryPointer probably has type []byte, in which case you need to convert the memory value to uint16 before you perform the bit shift:

    func DereferenceWord(addr uint32) uint16 {
        return uint16(memoryPointer[addr]) | uint16(memoryPointer[addr+1])<<8
    }
    

    In your current code, the bit shift overflows the byte type, meaning you'll always be left with 0.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)