views:

100

answers:

2

How can I implement the rightrotate (and leftrotate) operations on 32 bit integers without using any bitwise operations?

I need this because High Level Shader Language (HLSL) does not allow bitwise oeprations upon numbers, and I need rightrotate for a specific shader I'm trying to implement.

+4  A: 

For unsigned integers, divide by 2 and add 2^32 if the number was odd, for right rotate. For left, multiply by two and add 1 if it was above 2^32 - 1.

sje397
Note: depending on language, you might have to handle overflow and rounding. E.g. for left, you might have to subtract 2^32 before multiplying by 2.
sje397
If you don't need the carry bit to wrap around then you can simply divide and multiply by 2 for right and left rotate.
slebetman
@slebetman: that would then by definition be a shift rather than a rotate, surely?
Steve Jessop
How about for signed integers?
Martin
For signed integers, I'd just cast them to unsigned, do the rotate, and cast back :) But that's a bit language specific (not to mention lazy).
sje397
I can't do that kind of cast in HLSL as far as I know, otherwise that would be fine. The only casts in HLSL are the kind which will slice off some of the range.
Martin
It might depend a little on how you rotate. The easy way might be to multiply negative numbers by -1, rotate as above, then mutliply by -1 again...but, if you want to keep the sign, you would rotate on 31 bits (so replace 2^32 with 2^31 in the formula above - bit 32 will always be 0 for positive numbers).
sje397
I'm not sure, what kind of rightroate do I need for SHA256 and that'll tell you what type I need ;)
Martin
From what I can tell [here](http://en.wikipedia.org/wiki/SHA-2), they're unsigned.
sje397
Ok, I'll go with unsigned for now, and see if I get correct results :)
Martin
A: 

You typically can't. However, you CAN calculate the binary of a given number, rotate it, and then convert to Base 10 again.

Hope that helps.

Values: n is the number, 2^b is larger than the largest value of n.

I'm writing it in Lua. (.. is concat)

str = "" while b > 0 do if 2 ^ b < n then str = str .. "1" else str = str .. "0" end b = b - 1 end

The result is the final value of "str"

TaslemGuy
Right rotate is halving, left rotate is doubling.
slebetman
Only if the number is in a low-level language. High-level languages like Haskell have no constraints on memory size, so that would not always be true. For instance, Half of 1 is 0.5, not the int-limit.
TaslemGuy