c++ - 安全地将 2 个字节转换为短字节

标签 c++ pointers casting byte short

我正在为 Intel 8080 制作一个模拟器。其中一个操作码需要一个 16 位地址,通过组合 bc 寄存器(均为 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.bstate.c

关于c++ - 安全地将 2 个字节转换为短字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37176021/

相关文章:

c++ - 如何使用glCreateShaderProgram?

c++ - 不同线程上的 accept() 错误 10093

c++ - 在 VS2017 中使用整数作为 OutputDebugString

C 字符串指针函数 strdel

c - 如何连接 char* 字符串?

c++ - 我可以举一个现实生活中的例子,其中通过 void* 进行强制转换而 reinterpret_cast 无效吗?

c - qsort 函数指针的类型转换

c++ - 在 aux 方法中创建的 QWidget 不显示/绘制

python - 在 Python 中模拟指针以进行算术运算

c++ 在运行时检查对象是否实现了接口(interface)