Click to See Complete Forum and Search --> : How To Do Rotate Shift Operations


cheery_poori
March 1st, 2006, 05:38 AM
Hello..,

How to do Rotate Shift Operations in vc++. I am trying to encrypt some 4 byte data using shift operations. Please help me ..its urgent..

MrViggy
March 1st, 2006, 11:13 AM
IIRC, there is no rotate shift operators in C++, but there are shift operators. You'll have to write your own rotate, if you need it.

Shift right is '>>'; shift left is '<<':
unsigned int testNum = 8;
unsigned int res;
res = testNum >> 2; // res now has the value of '2'
Viggy

Hobson
March 1st, 2006, 11:38 AM
Maybe these would work:


template <class T>
inline T rotate_right(T arg, int count)
{
return (arg >> count) | (arg << (sizeof(arg) - count));
}

template <class T>
inline T rotate_left(T arg, int count)
{
return (arg << count) | (arg >> (sizeof(arg) - count));
}


Due to usage of 'operator >>' T has to be unsigned integral type.


EDIT:
Please tell me people which of following constructs would be legal:

variable definition: unsigned T mask = ((unsigned T) -1) >> sizeof(T); //maybe witn C++ cast instead of C cast
template parameter specification: template <class unsigned T> T fun(T arg)

or maybe one should use some compile time assert to be sure that arg is unsigned integer?

Hob

wildfrog
March 1st, 2006, 11:57 AM
or maybe one should use some compile time assert to be sure that arg is unsigned integer?
Does it really matter? The shift (and rotate) functions operates on a bit level, and shouldn't really care if you threat your variable as signed or not. They just look at the size of your type, and then shift/rotate each bit accordingly. Or, am I totally wrong here?

- petter

MrViggy
March 1st, 2006, 12:28 PM
Does it really matter? The shift (and rotate) functions operates on a bit level, and shouldn't really care if you threat your variable as signed or not. They just look at the size of your type, and then shift/rotate each bit accordingly. Or, am I totally wrong here?

- petter
Yep, I think it does matter (I think, I might be confusing C++ with Verilog here). If the value is signed, then shifts to the right will be sign extended. In other words, if you have the 8 bit signed pattern: 10000001; and shift right twice, you'd get: 11000000. The sign bit get's "duplicated".

Viggy

Sam Hobbs
March 2nd, 2006, 02:43 AM
If you want an answer specific to C++, then you should ask your question in a C++ forum.

Since you say you are using VC, perhaps you can use a solution that requires Intel X86 (Pentium) processors. If so, then you can write inline assembly to use the processor's shift instructions. If that is a possibility, then ask in the VC forum.