Shifty Thinking
Jim McCorison
Posts: 359
There are two, well, at least two, ways to shift bits. To shift left you can do either:
x = x * 2
or
x = x << 1
To me, the second version is clearer as to what is desired. But how much difference is there in the actual code generated for the BS2?
On a similar vein, you can add a bit to the rightmost bit of a variable using addition or a logical and. So, to accumulate bits into a variable you could:
x var nib
x = p0
x = x << 1
x = x | p1
or you could:
x = p0
x = x * 2
x = x + p1
Any thoughts?
Jim
x = x * 2
or
x = x << 1
To me, the second version is clearer as to what is desired. But how much difference is there in the actual code generated for the BS2?
On a similar vein, you can add a bit to the rightmost bit of a variable using addition or a logical and. So, to accumulate bits into a variable you could:
x var nib
x = p0
x = x << 1
x = x | p1
or you could:
x = p0
x = x * 2
x = x + p1
Any thoughts?
Jim
Comments
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Jon Williams
Applications Engineer, Parallax
Dallas, TX· USA
Now, on the BASIC Stamp, it does not matter much whether you use shift or multiply. The speed of the Stamp is determined by how many bits of information the processor has to read from the eeprom in order to execute the command, and the actual time for the execution is insignificant in relation to the read-in time. So, as Jon pointed out, you can pretty much judge the code size and also the speed of execution of a math operation by how many bits it takes in the memory map.
A math operation will take about 140 microseconds for most operations, although divide will take about 200 microseconds.
y = x takes about 190 microseconds
y = x * 2 takes about 140 microseconds longer, 330 microseconds.
y = x << 1 takes about 330 microseconds
y = x / 2 takes about 390 microseconds
y = x >> 1 takes about 330 microseconds <-- faster than /
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Tracy Allen
www.emesystems.com
Great. Thanks for the feedback. I think I will also do as Jon suggested as it will teach me a bit more about what goes on inside.
Jim