I'm working on a personal project to improve my knowledge on how a CPU works. So I'm doing a Intel 8080 emulator, which is a 8 bits microprocessor.
In the implementation of a RRC instruction, which example is this:
case 0x0f: {
uint8_t x = state->a;
state->a = ((x & 1) << 7) | (x >> 1);
state->cc.cy = (1 == (x&1));
}
I can't understand how this line is working.
state->a = ((x & 1) << 7) | (x >> 1);
I know it's supposed to move all the bits to the right by 1 position, but I can't figure out how.
I would appreciate if someone could provide me an example of what it's actually doing step by step.
state->a
is a uint8_t
which emulate the intel 8080 register named
A.
0x0f
is the HEX value for RRC.
The example has been provided by this page.
Lets study the steps in order:
uint8_t x = state->a;
Use a temporary variable for the current value of the A
register;(x & 1) << 7
shift the low order bit to the high order bit; (x & 1)
is the value of the low order bit as all other bits of x
are masked off.(x >> 1)
shift the other bits one place to the right (towards the lower bits).state->a = ((x & 1) << 7) | (x >> 1);
combine the bits from the previous 2 steps and store as the new value of the A
register;state->cc.cy = (1 == (x&1));
store the low order bit from the original value into the carry bit (this is the bit that was rotated into the high order bit).The effect of these steps is a rotation of the 8 bits one step to the right, with the low order bit landing into the carry flag. The 8080 reference card describes this as Rotate Accumulator Right thru Carry
.
Note that the steps can be simplified:
state->a = ((x & 1) << 7) | (x >> 1);
is the same as state->a = (x << 7) | (x >> 1);
because state->a
is a uint8_t
.state->cc.cy = (1 == (x&1))
is the same as state->cc.cy = x & 1;