位移操作导致结果为零时不应该这样。

huangapple go评论76阅读模式
英文:

Bit shift resulting in zero when it shouldn't

问题

我正在开发一个Chip8模拟器。Chip8指令以两个字节对的形式存储,我将其作为uint16处理。操作码的数据被编织到操作码本身中。例如,绘制精灵的操作码是0xDxyn,实际上操作码只是0xD000,最后三位是要绘制的x和y位置,n表示精灵的字节数。

在这个基础上,我一直在尝试使用简单的位移和掩码来提取这些数据,但是我得到的结果是0,而不是预期的值。例如:

//Opcode is = 0xD01F, of type uint16
x := int(c.Registers[((opcode >> 16) & 0x000F)])
y := int(c.Registers[((opcode >> 8) & 0x000F)])
size := int((opcode & 0x000F))

这应该解析为c.Registers[0]和c.Registers[1],但最终都变成了c.Registers[0]。Size的值是正确的,为15。为什么会这样呢?

英文:

I'm developing a Chip8 emulator. Chip8 instructions are stored as two byte pairs, which I handle as a uint16. The data for the opcodes is interwoven into the opcode itself. For example the opcode to draw a sprite is 0xDxyn, where the opcode is actually just 0xD000, with the last three places being the x and y location to draw, and the n being how many bytes the sprite is.

This is mind, I've been trying to extract this data using simple bitshifting and masking, but I keep getting 0 instead of the expected values. For example:

//Opcode is = 0xD01F, of type uint16
x := int(c.Registers[((opcode >> 16) & 0x000F)])
y := int(c.Registers[((opcode >> 8) & 0x000F)])
size := int((opcode & 0x000F))

This should resolve to c.Registers[0] and c.Registers[1], instead both end up c.Registers[0]. Size comes out correctly 15. Why is this?

答案1

得分: 5

如果将一个16位数向右移动16位,你将把所有数据都移出。

要获取x,你需要向右移动8位,要获取y,需要向右移动4位。(记住:每个十六进制数字是4位)

英文:

If you shift a 16 bit number 16 places to the right you've shifted all of the data out.

To get x you need to shift 8 bits and to get y, 4 bits. (Remember: each hex digit is 4 bits)

huangapple
  • 本文由 发表于 2014年8月7日 10:45:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/25173345.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定