A bit of a philosophical question, I suppose.
The C language has the standard set of bit-wise operations, including OR
, AND
, XOR
, SHIFT LEFT/RIGHT
, and NOT
. Why aren't rotate left/rotate right operators or functions included in the language?
These operators are of the same complexity as other bit-wise operators and normally require a single assembly instruction, like the others. Besides, I can think of a lot of uses for rotate operator, probably not less than, say, xor
operator - so it sounds a bit strange to me that they aren't included in C along with the rest.
If you do need to rotate in C or C++, there's a separate FAQ question about best-practices for it. Discussion of that is off-topic for this question.
I think it's because there are two types of rotations: with and without carry, which makes the rotation to be done differently, according to the resulting machine's CARRY flag (1 or 0). That would imply implementing a total of 4 operators, thus making the language unnecessarily complex, provided that rotation can be simply implemented as @Aniket has shown.
EDIT:
Nevertheless, shifting may also be done signed and unsigned. Actually Javascript has both operators, AFAIK. However, since C supports signed and unsigned variables, I think it has no sense to perform signed shifts, because the compiler should know whether we are shifting a signed or unsigned variable. Signed/unsigned shifts are useful for arithmetical computations, and a C compiler may use them to generate the assembly code. For instance, many arithmetical operations such as multiplying or dividing by a power of 2 are translated by the compiler into shift operations. The only reason we have shift operators in C is for working with bitmasks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With