sprocket12
sprocket12

Reputation: 5488

How to read a 16 bit value from memory

I have a 4096K binary in memory, in little-endian format. I want to read a couple of the 8 bit values as a uint16_t how do I do it in the most performant manner?

void execute_cart (i6507_t* cpu, uint8_t* memory) {
    // uint16_t start = memory[0xFFFC]; // this address contains a 16 bit value
}

Update: I am running on x86-64 arch, the binary is for an old 8 bit console.

Upvotes: 0

Views: 701

Answers (1)

dbush
dbush

Reputation: 223689

You'll need to read two bytes separately and combine them into a single uint16_t variable:

unsigned offset = 0xfffc;
uint16_t start = memory[offset];
start |= (uint16_t)memory[offset+1] << 8;

If memory starts an an address that is well aligned and if the offset is a multiple of 2, then you can do this in a single read:

uint16_t start = *(uint16_t *)&memory[0xfffc];

Upvotes: 1

Related Questions