Shop OBEX P1 Docs P2 Docs Learn Events
Shifty Thinking — Parallax Forums

Shifty Thinking

Jim McCorisonJim McCorison Posts: 359
edited 2005-01-06 18:42 in BASIC Stamp
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

Comments

  • Jon WilliamsJon Williams Posts: 6,491
    edited 2005-01-06 02:16
    The Memory Map will tell all. Write a couple of identical programs using the different methods, then check to see who many program bytes are used for tokens.

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Jon Williams
    Applications Engineer, Parallax
    Dallas, TX· USA
  • Tracy AllenTracy Allen Posts: 6,658
    edited 2005-01-06 18:12
    If you were writing machine language programs, you would always prefer the shift over the multiply when appropriate, because it would occupy much less code and also run faster. The general purpose multiply requires many shifts and adds in a loop, unless the processor happens to have a hardware multiplier. There is less difference with ADD vs OR, because all processors have either of those as elementary operations that take about the same amount of code and time.

    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
  • Jim McCorisonJim McCorison Posts: 359
    edited 2005-01-06 18:42
    Tracy,

    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
Sign In or Register to comment.