Hi there. I do not understand the following line of code. program_counter = (memory[0xFFFD] << 8) | memory[0xFFFC];

The array memory[] represents the memory space of our processor. The starting address for
a 6502 program is stored at location $FFFC and $FFFD in memory. The 6502 stores
addresses in low byte/hi byte format, so $FFFD contains the upper 8 bits of the
address and $FFFC the lower 8 bits. This line assembles the 2 bytes into a 16-
bit address.

I am aware of bit manipulation in C, so I understand what the line of code "does", so to speak, but I'm not sure what it is we are achieving by doing this.

Using the following binary number as an example: 0111001101100001

Are we saying that memory[0xFFFD] holds 0000000001110011, and memory[0xFFFC] holds 0000000001100001?

Because then (memory[0xFFFD] << 8) | memory[0xFFFC] == 0111001101100001.

But the author doesn't make this clear so I'm not sure. Thanks for any clarification.

Edit: The author says "This line assembles the 2 bytes into a 16-bit address.", so $FFFD and $FFFC only hold a byte each. Then surely (memory[0xFFFD] << 8) will simple equal 00000000?

>But the author doesn't make this clear so I'm not sure.
Your analysis looks good to me.

>Then surely (memory[0xFFFD] << 8) will simple equal 00000000?
Integral promotions are performed on both of the operands to the << operator, so that snippet would only be shifting away the relevant bits if the size of int were the same as the size of char.

Sorry, I'm not following.

My example in my initial post is silly seeing as memory[n] can only hold 1 byte.

The way I see things is, whatever memory[0xFFFD] holds, shifting it left 8 places will result in 00000000. So then when we come to the OR part, we are just left with '00000000 | memory[0xFFFC]' which is equal to memory[0xFFFC]. But I'm clearly wrong.

>My example in my initial post is silly seeing as memory[n] can only hold 1 byte.
Given the assumption that memory[n] remains one byte throughout the shift, which is false. In this code:

(memory[0xFFFD] << 8)

memory[0xFFFD] is converted to int before the shift is performed. If int happens to be an 8-bit quantity, then not only will the result probably be 00000000, you'll also have invoked undefined behavior by shifting beyond the bit count of the data type. However, if int is 2 bytes, for example, then 01110011 will become 0000000001110011 after the integer promotion and the shift makes perfect sense.

Ah OK. I didn't know it would be converted to an int. I take it this is because we are storing it in 'program_counter' which is an int?

>I take it this is because we are storing it in 'program_counter' which is an int?
No, it's because the shift operator is defined to perform that conversion on both operands, as I stated in my first reply.

This article has been dead for over six months. Start a new discussion instead.