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->ais auint8_twhich emulate the intel 8080 register named A.0x0fis 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 theAregister;(x & 1) << 7shift the low order bit to the high order bit;(x & 1)is the value of the low order bit as all other bits ofxare 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 theAregister;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 asstate->a = (x << 7) | (x >> 1);becausestate->ais auint8_t.state->cc.cy = (1 == (x&1))is the same asstate->cc.cy = x & 1;