View previous topic :: View next topic |
Author |
Message |
rnielsen
Joined: 23 Sep 2003 Posts: 852 Location: Utah
|
Shift << or >> question |
Posted: Mon Jul 19, 2004 5:19 pm |
|
|
I believe that when you do a shift left or right, << or >>, that zero's will always be inserted into the bits that are emptied. For example, if I do this:
variable = 10100111
then
variable = variable << 4;
the result is 01110000.
Is this what you have experienced? I just want to make sure before I try and trust things to work this way.
Ronald |
|
|
Haplo
Joined: 06 Sep 2003 Posts: 659 Location: Sydney, Australia
|
|
Posted: Mon Jul 19, 2004 6:13 pm |
|
|
Correct. Zeros will be shifted in. |
|
|
ckielstra
Joined: 18 Mar 2004 Posts: 3680 Location: The Netherlands
|
|
Posted: Tue Jul 20, 2004 1:03 am |
|
|
For the left shift << it is true that always zero's will be shifted in.
For the right shift >> it is not specified in the C standard and left to the compiler builder. For unsigned data you always want a zero to be shifted in, but for signed data you want to shift in the same bit as already present in the most significant position.
If you want to be sure about the >> operation use the shift_right() function in which you can specify the bit to be shifted in.
Update: Did a small test on the PIC18F458 and PCH3.187.
A zero is always shifted in for both << and >> independent of signed or unsigned data. The shift_right() function is just as efficient as the << or >> operator. Code: | .................... int8 Temp;
.................... unsigned char uTemp;
.................... signed char sTemp;
....................
.................... uTemp = 0;
*
00EE: CLRF 19
.................... sTemp = -1;
00F0: MOVLW FF
00F2: MOVWF 1A
.................... uTemp = uTemp >> 1;
00F4: BCF FD8.0
00F6: RRCF 19,F
.................... shift_right(&uTemp, 1, 0);
00F8: BCF FD8.0
00FA: RRCF 19,F
.................... shift_right(&uTemp, 1, 1);
00FC: BSF FD8.0
00FE: RRCF 19,F
.................... sTemp = sTemp >> 1;
0100: BCF FD8.0
0102: RRCF 1A,F
|
|
|
|
|