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 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据