Full Version: Rotate left 2 bits (like assembler)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2 3 4 5 6 7 8 9 10
Using only QB instructions, no assembler, perform the same function that a "rol" does in assembler.

For this exercise, take a given 16 bit value and do a rotate left 2 bits.
Could you please explain what ROL does... I've tried some explanations on the web but they're all too fuzzy. I believe it's not the same as doing shl?
It's the same as SHL, but the bits that are shunted off of the left-hand-side and replaced onto the right-hand-side.

It's basically:

int rol(int original, int shiftBy)
    return (original << shiftBy) | (original >> (16 - shiftBy);
Here's an example of a rotate left 2 bits.

If the original variable contains:
rotating it left 2 bits, would change the variable to:

I believe the following will rotate QB signed 16-bit integers 2 to the left. Note: this would be simpler if qb had unsigned data types.

INPUT "gimme a number"; a
PRINT a; " (dec) == "; HEX$(a); " (hex)"

SignBit = a < 0         ' true if 16th bit is on
'PRINT SignBit
nextBit = ((a AND &H4000) = &H4000)  ' true if 15th bit is on
'PRINT nextBit
newSignBit = ((a AND &H2000) = &H2000)  ' true if 14th bit is on
'PRINT newSignBit

a = a AND &H1FFF '&H1fff == 0001 1111 1111 1111...clear the bits that will fall off before shifting to prevent overflow errors

a = a * 4  ' shift left 2 bits
a = a + (-2 * SignBit) 'add bit to 2's place
a = a + (-1 * nextBit) 'add bit to 1's place

IF newSignBit THEN a = a OR &H8000  'add sign if needed

PRINT "your number rotated left 2 bits is"
PRINT a; " (dec) == "; HEX$(a); " (hex)"


Not the most elegant solution, but...

Your solution may not be the most elegant, but it addresses all the salient points of the problem.

Give me a chance to do some testing of it, and let you know how it goes.
Nice job, Mango, your solution works perfectly.

I tested it with a little program from 0 to 32768, verifying the results against my own solution, and in so doing found a bug in mine. :oops:

The big difference between yours and mine is that I did all the work using LONG integers. This enabled me not to have any IF statement.

However, a careful look at yours shows a very clever setup of bitmasks for Signbit and newbit, which in retrospect makes it an elegant solution after all, plus it works!

Congratulations, you are the winner so far. Big Grin

same as x <<= 2


same as x <<= 2
is the same as a shift left of 2 bits.
The original left 2 bits get lost, plus if the original leftmost bit was a 1, you'll get an overflow.
The challenge is to ROTATE the 2 leftmost bits into the 2 rightmost bit positions of the result. Please see the example.

I don't know what you mean by:
x <<= 2
What language is this in?
Quote:I don't know what you mean by:
x <<= 2
What language is this in?

C/C++/Java/Perl/PHP/probably others.
Pages: 1 2 3 4 5 6 7 8 9 10