Search code examples
c++pointerscastingbyteshort

Safely convert 2 bytes to short


I'm making an emulator for the Intel 8080. One of the opcodes requires a 16 bit address by combining the b and c registers (both 1 byte). I have a struct with the registers adjacent to each other. The way I combine the two registers is:

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)]

I was thinking I can just OR them together, but that doesn't work.

short address = state.b | state.c

Another way I tried doing this was by creating a short, and setting the 2 bytes individually.

short address;
*reinterpret_cast<byte*>(&address) = state.b;
*(reinterpret_cast<byte*>(&address) + 1) = state.c;

Is there a better/safer way to achieve what I am trying to do?


Solution

  • short j;
    j = state.b;
    j <<= 8;
    j |= state.c;
    

    Reverse the state.b and state.c if you need the opposite endianness.