Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you control what a bitwise right shift will fill in C?

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

like image 803
Daniel Scocco Avatar asked Dec 07 '11 20:12

Daniel Scocco


People also ask

How does right shift work in C?

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).

Does C perform logical right shifts?

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.

Which operator is used for right shifting in C?

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.


1 Answers

Cast the number to unsigned and then shift. That will force a 0-fill.

like image 163
dan04 Avatar answered Sep 20 '22 18:09

dan04