PDA

View Full Version : Shifting bits



Charles Linquis
- 22nd February 2011, 05:15
I need to manipulate the bits in a 40 bit number.

Is it correct to assume that if I make an array "bignumber VAR BYTE[5]"
The bits will be stacked together in memory?

Assuming the above is true:

I need to shift bits 7-14 (starting from the right - byte5.0) Left one position,
bits 15-22 left two positions, bits 23-30 left 3 positions, and bits 31-36 left 4 positions.
Then I need to stuff the "empty" spaces with "1" or "0".

Does anyone have any insight on how I might do this?

cncmachineguy
- 22nd February 2011, 14:35
Hi Charles,
This is my third attempt to respond to this. I know how to do it, just can't seem to make it make sense on paper. Mind you this is just 1 way, if I can figure out how to say the others i will.



'assuming:
'byte 4 is 0-7
'byte 3 is 8-15
'byte 2 is 16-23
'byte 1 is 24-31
'byte 0 is 32-39

BigShift:
' first part 31-36 left 4 places
byte0 = byte0 <<4
byte0.3 = byte1.7
' second part 23-30 left 3 places
byte0.1 = byte1.6
byte0.0= byte1.5
byte1 = byte1<<3
byte1.2 = byte2.7
' third part 15-22 left 2 places
byte1.0=byte2.6
byte2 = byte2<<2
byte2.1 = byte3.7
' last part 7-14 left 1 place
byte3<<1
byte3.0=byte4.7

'''''''''done


Not very elegent, but if i kept my bits in order, I think it works. The shifted bits will leave 0 in their place, the assignments will leave original intact

Charles Linquis
- 22nd February 2011, 17:46
I was thinking the same thing.

The whole "algorithm" is :

Given any number of bytes

OutputByte 0, bits 0-6 = InputBytes 0-6
OutputByte 0, bit 7 = 1 IF there are more bytes to follow, 0 if no more bytes (so always zero in this case).

OuputByte 1,bits 0-6 = InputByte (shifted - bit 0 is the 7th bit of inputByte 0)
OutputByte 1 ,bit 7 = 1 IF there are more bytes to follow (so always 1)

OutputByte 2,bits 0-6 = data (shifted twice - bit 0 is bit 6 of InputByte1,bit 1 is bit 7 of inputByte1
Output?Byte2,bit7 = 1 IF there are more bytes to follow (so always 1).

Data is read MSB first, so

If input = $7F, output = $7F
If input = $80, ouput = $8100 (seventh bit of byte 0 shifted to bit 0 of byte 2, MSb of byte 1 set because there is one more byte to go (byte 0 is all "0"))

Likewise $67CD is converted to $81CF4D

There has got to be some semi-elegant way.

Thanks for getting me started.