Getting unexpected values when trying to set Bits

I'm experimenting setting bits to get a feel for how it is done. In this case I want to change the value five to -5 by changing the sign bit.

1
2
3
4
5
6
7
8
9
#include <iostream>

int main()
{
    short signed int mynumber = 5;
    cout << mynumber << endl;
    cout << (mynumber | 0x8000);
    return 0;
}


Unfortunately the results are far from -5 and I'm at a loss as to why this is happening.

1
2
3
4
// RESULTS
5
32773
 
Usually two's complement representation is used to represent signed values so in that case 5 is stored as 0000 0101 while -5 is stored as 1111 1011.

http://en.wikipedia.org/wiki/Two%27s_complement
Oh and the reason why you didn't get a negative value at all was because (mynumber | 0x8000) will actually give you an int so you have to cast it back to a short if that's what you want.

 
cout << static_cast<short>(mynumber | 0x8000);  // Prints "-32763". 
Ok thankyou for your time I seem to have to investigate this two's compliment representation. Somehow I was led to believe only the sign bit had to be flipped.
Ok I understand two's compliment now. For anyone else who would like an explanation I found http://www.youtube.com/watch?v=9W67I2zzAfo easier to understand than wikipeida. I modified the code to represent two's compliment and took the equation out of the stream so not to bother with recasting to a short. Here is the code now.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

#include <iostream>
using namespace std;

int main()
{
	short int mynumber = 5;
	cout << mynumber << endl;
	mynumber = ( ~mynumber + 0x0001 );
	cout << mynumber;
	
	return 0;	
}


This does indeed give me -5. Thankyou Peter87.
Last edited on
Topic archived. No new replies allowed.