E
E
Egorithm2016-06-16 16:37:02
C++ / C#
Egorithm, 2016-06-16 16:37:02

Why is there a minus in bit shifts?

Here is the code:

int a=-7;
a<<=1;
a>>=1; 
printf("%d\n",a);

The binary representation is -7 (if I understand correctly, the sign is stored in the first bit):
10000111
If you make a left shift, you should get:
00001110
Then a right shift:
00000111
Which in the binary representation is 7 . But I had -7 as it was , and it remains.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Movchan, 2016-06-16
@EgoRusMarch

if I understand correctly, the sign is stored in the first bit

Incorrect, negative numbers are represented with two's complement .
PS This is not to expand the range of possible values.
The additional code allows you to replace the subtraction operation with the addition operation and make the addition and subtraction operations the same for signed and unsigned numbers, which simplifies the computer architecture.

W
wrench10x12, 2016-06-16
@wrench10x12

The binary representation is -7 actually 11111001 * **
*if you don't take exotic architectures into account
**assuming that int suddenly became single byte

V
Vasily, 2016-06-16
@Foolleren

there are 4 kinds of shifts, look in the debugger and see what the compiler actually put in there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question