Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 515
Greg M Avatar asked Oct 15 '25 21:10

Greg M


1 Answers

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

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

like image 178
David Schwartz Avatar answered Oct 17 '25 10:10

David Schwartz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!