When I use the >> bitwise operator on 1000 in c++ it gives this result: 1100. I want the result to be 0100. When the 1 is in any other position this is exactly what happens, but with a leading 1 it goes wrong. Why is that and how can it be avoided?
-
1what data type is your variable holding `1000`? – Joe May 19 '20 at 15:48
-
4Right shifting on **signed numbers** can do that. Change your type to **unsigned int**. – selbie May 19 '20 at 15:48
-
https://en.wikipedia.org/wiki/Arithmetic_shift – selbie May 19 '20 at 15:49
-
1Is this a hexadecimal number? A binary number? The integer literal "1000" (decimal 1000) should only be interpreted as negative if assigned to an 8-bit signed char or something like that. – JohnFilleau May 19 '20 at 15:56
2 Answers
The behavior you describe is coherent with what happens on some platforms when right-shifting a signed integer with the high bit set (so, negative values).
In this case, on many platforms compilers will emit code to perform an arithmetic shift, which propagates the sign bit; this, on platforms with 2's complement representation for negative integers (= virtually every current platform) has the effect of giving the "x >> i
= floor(x/2i)" behavior even on negative values. Notice that this is not contractual - as far as the C++ standard is concerned, shifting negative integers in implementation-defined behavior, so any compiler is free to implement different semantics for it1.
To come to your question, to obtain the "regular" shift behavior (generally called "logical shift") you have to make sure to work on unsigned
integers. This can be obtained either making sure that the variable you are shifting is of unsigned type (e.g. unsigned int
) or, if it's a literal, by putting an U
suffix to it (e.g. 1
is an int
, 1U
is an unsigned int
).
If the data you have is of a signed type (e.g. int
) you may cast it to the corresponding unsigned
type before shifting without risks (conversion from a signed int to an unsigned one is well-defined by the standard, and doesn't change the bit values on 2's complement machines).
- Historically, this comes from the fact that C strove to support even machines that didn't have "cheap" arithmetic shift functionality at hardware level and/or didn't use 2's complement representation.

- 123,740
- 17
- 206
- 299
As mentioned by others, when right shifting on a signed int, it is implementation defined whether you will get 1s or 0s. In your case, because the left most bit in 1000 is a 1, the "replacement bits" are also 1. Assuming you must work with signed ints, in order to get rid of it, you can apply a bitmask.

- 75
- 1
- 13
-
1Right shifting on a negative signed int is implementation defined. Right shifting on a positive signed int is well defined. – JohnFilleau May 19 '20 at 15:59