As far as I know when you use a left shift bitwise operator in C it's guaranteed that the vacant bits will be filled with 0s. However, I've read that the right shift is implementation-dependent, meaning in some machines the vacant bits will be filled with 0s, in others they will be filled with 1s.
I am using the right shift in a program, and indeed my machine is filling the vacant bits with 1s. Problem is I would need it to fill with 0s instead.
Is there a way to force 0s to be used on right shifts?
One solution would be, after the right shift is applied, to create a mask like 011111111 and then apply a bitwise AND, which will change the leftmost 1 that was inserted to a 0.
But this is cumbersome and wastes time. If there was a way to tell my machine to fill right shifts with 1s it would be much easier.
Thanks
Right shift >>It shifts each bit in its left operand to the right. The number following the operator decides the number of places the bits are shifted (i.e. the right operand).
Many C compilers choose which right shift to perform depending on what type of integer is being shifted; often signed integers are shifted using the arithmetic shift, and unsigned integers are shifted using the logical shift.
It is a bitwise operator that we use in the C language for operating on bits. The right shift operator is binary- which means that the working of this operator would require two of the operands. We represent the right shift operator using the >> sign.
Cast the number to unsigned
and then shift. That will force a 0-fill.
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