Public Group

# compl

This topic is 5068 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

can someone explain to me why i get -2 when i run this code int num = 1; cout << compl(num) << endl;

##### Share on other sites
In C (and C++), compl is an equivalent keyword for ~, which is the bitwise complement operator. That is, all the bits in num get flipped.

000000000000000000000000000000012 becomes 111111111111111111111111111111102 which is the 32-bit 2-complement signed representation of -2.

##### Share on other sites
is it possible to make ~ work with only one byte so I don't get this problem?

##### Share on other sites
Not without you explaining what compl() is :P

I assume it's the one's complement...flip all the bits (so all 0s become 1s, all 1s become 0s). This leaves you with a number that has all bits set to 1 except the least significant bit.

00000000000000000000000000000001 => 1
(take one's complement)
11111111111111111111111111111110 => -2

(since this is a signed integer, the most significant bit being one indicates that the value is negative).

Regards,
Jeff

##### Share on other sites
First you need to know what the compl function does, which is the
same as ~. That is to say, it returns the number with all bits reversed. So if you were working with unsigned 8 bit numbers

00000001 = 1
11111110= ~1 = 254

The difference is that int is by default signed. In this case you need to refer to the two's complement in reference to the bevahior of negative numbers in binary. The short and easy version is basically that:

11111110
+ 1
---------
11111111
+ 1
---------
100000000

And because 100000000 is 9 bits, instead of 8, the number is truncated to just plain zero. 11111110 as a signed char is -2 because adding 2 to it makes zero.

For more reading on the two's complement, look here.

 Figures I was beaten to it. Many times. [sad]

##### Share on other sites
Quote:
 Original post by sevakis it possible to make ~ work with only one byte so I don't get this problem?

Maybe you are looking for the logical-not operator ?

int num = 1;
cout << !num << endl;

Which prints 0, or do you really mean

int num = 1;
cout << static_cast<int>(static_cast<unsigned char>(~num)) << endl;

Which yields 254 (i.e. 000000000000000000000000111111102)

##### Share on other sites
Quote:
 Original post by FrunyIn C (and C++), compl is an equivalent keyword for ~, which is the bitwise complement operator.

Interesting, never knew that...

##### Share on other sites
Quote:
 Original post by sevakis it possible to make ~ work with only one byte so I don't get this problem?

What are you trying to do exactly?

##### Share on other sites
I guess I didn't realy understand what ~ meant. Thanks now I get it. I guess what I was trying to do was use the ~(compl) like a !(not) opertator

• 39
• 12
• 10
• 10
• 9
• ### Forum Statistics

• Total Topics
631365
• Total Posts
2999590
×