Why doesn't C have rotate left/right operators

2020-03-01 08:16发布

问题:

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 7 years ago.

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.

回答1:

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.



回答2:

C doesn't have rotate-left and rotate-right for binary. You can code rotate left and rotate-right functions yourself. But as per standards: nope.

Simple rotate-left :

int rotate_left(int num, int bits)
{
  return ((num << bits) | (num >> (32 -bits)));
} 

int rotate_right(int num, int bits)
{
  return ((num >> bits) | (num << (32 -bits)));
}

The above functions will work with 32 bit integers only :)

Now for the philosophy: C was meant to be portable as much as possible. That's what the standards team want it to be "a portable assembler". There is no guarantee that rol and ror is present on architectures of the future. Or might behave differently. Hence it was kept away from standards.