Go Down

Topic: Bitshift help. (Read 1 time) previous topic - next topic

Pavilion1984

Quote
Code:
  b = 1 << 1 | 1;
use instead:


Code:
  b = (b << 1) | 1;
to produce 0b00000001 -> 0b00000011 -> 0b00000111 ...

or

Code:
  b = (b >> 1) | 0x80;
to produce 0b10000000 -> 0b11000000 -> 0b11100000 ...;

This is also considerably faster.
dhenry, i have tested what you have said and it doen't work.

WizenedEE


I have just tested that and yes it does work, great. What is the -1 doing in this if you don't mind me asking (i have not used these functions before so this is new to me)? If am going to use it i need to know what it is doing lol but thanks a bunch to WizenedEE and Grumpy_Mike.


Code: [Select]

1<<5 = 00100000
00100000 -1 = 00011111
~00011111 = 11100000

Grumpy_Mike

Quote
What is the -1 doing

Subtracting one.

Any power of two can be expressed as a 1 followed by several zeros, the number depending on the power. If you subtract one from the resulting number you get zero followed by several ones.
If you want the inverse of this, for example you have 0001 1111 and you want 1110 0000 then just take the inverse of the number. There are many ways of doing this, here are some, assume the number you want to invert is in a vaiable called b

Code: [Select]

b = ~b; // note this is a tilda not a minius
b = b ^ 0xff // exclusive or inverts all bits in a variable that have a matching one in the number you are exoring it with
b = not(b);

Pavilion1984

Ok thanks alot. So i have 2 options of code to use

1 - the lookup table
or
2 - the bitshift function

is one better then the other or just personal preference? I will be using the i2c driver for my display and this RPM stuff is just the start of it. I now need to find out the best way to flash the last "on" LED in 11111000 if a variable has been set to 5 or if the variable has been set to 6 flash the last "on" LED in 11111100.

Grumpy_Mike

It is always better to use an algorithm than a look up table in my opinion.

For flashing create a number with a one in the bit you want to flash using bit shift operations. Then exclusive or this number with your byte save and output.
Every exclusive or operation will toggle the bit you set in the number.

Go Up