简体   繁体   中英

Why would someone bitwise AND an 8-bit value with a 16-bit mask in C?

I am trying to replicate Javidx9's NES/MOS6502 CPU code in C# as an academic exercise and I am having trouble understanding the logic behind the implementation of the Zero-Page Addressing Mode. Specifically, I am looking at this code :

// Address Mode: Zero Page
// To save program bytes, zero page addressing allows you to absolutely address
// a location in first 0xFF bytes of address range. Clearly this only requires
// one byte instead of the usual two.
uint8_t olc6502::ZP0()
{
    addr_abs = read(pc);    
    pc++;
    addr_abs &= 0x00FF;
    return 0;
}

I struggle to understand why addr_abs &= 0x00FF; is there, uint16_t addr_abs is 16 bits but uint8_t read(uint16_t a); returns an 8-bit value anyways, so the upper 8 bits (MOS6502 is little-endian) would be 00'd out by default? Am I missing something about how the C compiler/x86 ISA works?

You're correct addr_abs &= 0x00ff isn't needed.

uint16_t x = n where n is an unsigned 8-bit number (which is the case here). x would have it's upper 8 bits cleared. As @tadman stated, there might have been a different method used previously to store the value into addr_abs which didn't clear the upper 8 bits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM