nihulus
nihulus

Reputation: 1495

shifting in C and assembly

Consider the following C code that writes and reads to and from memory mapped I/O.

volatile int* switches = (volatile int*) 0x1b430010; 
volatile int* leds = (volatile int*) 0xabbb8050; 
int temp = ((*switches) >> 6) & 0x3; 
*leds = (*leds & 0xff9f) | XXX;

From the C code above it is possible to derive that some bits are read from the 16-bit switch port and used to turn on or off some LEDs, without affecting the other LEDs on the 16-bit LED port. One missing expression is marked as XXX. Write out what expression XXX should be, so that the LEDs are correctly turned on or off.

The answer is XXX = temp << 5. When i try to translate to assembly and calculate in bits, I got temp is 0 after ((*switches) >> 6) & 0x3;, so why temp << 5 is valid here because shifting 0 does not make any different? (maybe I misscalculated, can provide all my calculations in bits if neccessary)

Upvotes: 0

Views: 240

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140168

0xff9f is 1111111110011111 in binary. The mask zeroes bit 5 and 6, keeps the others.

temp is a value on 2 bits because the code and-masks with 0x3, 11 in binary (all other bits are zeroed). You have to shift it left 5 times to be able to insert in the final value by | masking.

(The fact that you're getting 0 for temp is either a bug or expected depending on the input data, it doesn't change the answer above)

Upvotes: 3

Related Questions