You are not logged in.

#1 2010-10-27 07:48:30

toffyrn
Member
Registered: 2008-10-07
Posts: 221

[SOLVED] bitshift on negative integers.

Doing a right bitshift on +5 gives me +2 which is logical to me:
0101 => 0010

However using a negative number -5 results in -3:
-0101 => -0011 ???
Can someone explain why the last zero flipped to a one instead?

chrishir@bra ~/Desktop/test $ cat test.cpp
#include <stdlib.h>
#include <iostream>

int main()
{
   int x = -5;
   int y = x >> 1;

   std::cout << x << std::endl;
   std::cout << y << std::endl;

}
chrishir@bra ~/Desktop/test $ ./test.bin
-5
-3
chrishir@bra ~/Desktop/test $ 

Last edited by toffyrn (2010-10-27 08:05:08)

Offline

#2 2010-10-27 07:57:37

Barrucadu
Member
From: York, England
Registered: 2008-03-30
Posts: 1,158
Website

Re: [SOLVED] bitshift on negative integers.

Negative numbers are represented using two's complement:

-5 = 1011 (bit patterns obviously truncated, but all the missing bits are '1's)
-3 = 1101

When bit shifting a signed value, the sign bit is preserved. Hence, bit shifting the -3 right by one would give -2 (1110), and again would give -1 (1111).

Last edited by Barrucadu (2010-10-27 07:59:08)

Offline

#3 2010-10-27 08:04:28

toffyrn
Member
Registered: 2008-10-07
Posts: 221

Re: [SOLVED] bitshift on negative integers.

Thanks...

So my understanding of how negative numbers are stored was wrong.
I understood it now smile

Last edited by toffyrn (2010-10-27 08:06:39)

Offline

#4 2010-10-27 14:05:58

tavianator
Member
From: Waterloo, ON, Canada
Registered: 2007-08-21
Posts: 859
Website

Re: [SOLVED] bitshift on negative integers.

Actually, C and C++ don't guarantee that two's complement is used to represent signed integers, but they do guarantee that the result of shifting a signed number to the right is always rounded down (towards negative infinity).

Offline

Board footer

Powered by FluxBB