Say I have a function like this:
inline int shift( int what, int bitCount )
{
return what >> bitCount;
}
It will be called from different sites each time bitCount
will be non-negative and within the number of bits in int
. I'm particularly concerned about call with bitCount
equal to zero - will it work correctly then?
Also is there a chance that a compiler seeing the whole code of the function when compiling its call site will reduce calls with bitCount
equal to zero to a no-op?
1 in binary is 0001 , then bitshifting it by 0 won't do anything, which aligns with what you observed. So any number x << 0 is equivalent to x * 2^0 , which is x * 1 , which is just x .
The bitwise shift operators are the right-shift operator ( >> ), which moves the bits of an integer or enumeration type expression to the right, and the left-shift operator ( << ), which moves the bits to the left.
The unsigned right shift operator ( >>> ) (zero-fill right shift) evaluates the left-hand operand as an unsigned number, and shifts the binary representation of that number by the number of bits, modulo 32, specified by the right-hand operand.
One simple and good way to encrypt data is through rotation of bits or sometimes called bit shifting.
According to K&R "The result is undefined if the right operand is negative, or greater than or equal to the number of bits in the left expression's type." (A.7.8) Therefore >> 0
is the identity right shift and perfectly legal.
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