We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
I am facing a problem in using the right shift operator in C with keil. The instruction is:for(i=0;i<=8;i++) { j=sum>>i; } where sum= 32 bit no. the instruction is not executed if the syntax is as shown above. but if i write a numerical value instead of using the variable name 'sum' then the instruction is easily executed. i need to use the variable name only. how do i fix this problem?
My interpretation of the original post is that he wants to do something to each of the least significant 8 bits one at a time.
for (i = 0; i < 8; ++i) { bit = (sum >> i) & 1; DoSomething(bit); // called for bit 0, bit 1... bit 7 }
This should work, though it's a little inefficient because it shifts too much. It also shifts a U32 unnecessarily, which will take time on an 8051. I'd probably write code more like:
U8 temp = (U8)sum; for (i = 0; i < 8; ++i) { DoSomething (temp & 1); temp >>= 1; }
so that you only have to shift an 8-bit quantity, and you only do 8 1-bit shifts.
So, if my interpretation of the OP is correct, the question is why (sum >> i) doesn't work in the posted code, though (sum >> 1) does.
How about posting the assembly code output from the .cod file in both cases?