我正在为 Intel 8080 制作一个模拟器。其中一个操作码需要一个 16 位地址,通过组合 b
和 c
寄存器(均为 1 字节)。我有一个寄存器彼此相邻的结构。我结合这两个寄存器的方式是:
using byte = char;
struct {
... code
byte b;
byte c;
... code
} state;
...somewhere in code
// memory is an array of byte with a size of 65535
memory[*reinterpret_cast<short*>(&state.b)]
我想我可以将它们OR
放在一起,但这行不通。
short address = state.b | state.c
我尝试这样做的另一种方法是创建一个短片,然后分别设置 2 个字节。
short address;
*reinterpret_cast<byte*>(&address) = state.b;
*(reinterpret_cast<byte*>(&address) + 1) = state.c;
是否有更好/更安全的方法来实现我想要做的事情?
最佳答案
short j;
j = state.b;
j <<= 8;
j |= state.c;
如果您需要相反的字节顺序,请反转 state.b
和 state.c
。
关于c++ - 安全地将 2 个字节转换为短字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37176021/