You are not logged in. Please login at www.codechef.com to post your questions!

×

~ Operator

Hi, Can anyone please tell me how does this ~ operator works? I am aware of other bitwise operators but I am unable to understand this NOT operator. C++ is showing ~1= -2 , ~2=-3 etc.. How is it happening? :/

Please help me.. Thanks.. :)

asked 04 Apr '13, 18:30

guptakeshav's gravatar image

5★guptakeshav
1222
accept rate: 0%


@guptakeshav : Numbers or integers are represented as 2's complement notation binary numbers . You can read more about it here : http://en.wikipedia.org/wiki/Two%27s_complement Brief Explanation : first bit is sign bit . '0' for positive numbers and '1' for negative numbers . So positive numbers are : 000..000 (for 0) , 000...001 (for 1) , 000....0010 (for 2) and so on . Since zero is already represented in positive numbers , no negative zero is defined . So negative numbers are : 11....111 ( for -1 ) , 11....110 ( for -2 ) , 11....1101 ( for -3 ) eg 1. : So 1 is represented as 00....1 in binary , when you take ~ of this it becomes 1111....10 in binary which is representation of -2 . eg 2. : So 2 is represented as 00....10 in binary and when you take ~ of this it becomes 1111101 in binary which is representation of -3 . If you have any doubts why positive numbers follow a certain fashion or negative numbers follow a certain fashion in 2's complement notation , you should read the wikipedia entry which will also tell you how to obtain a 2's complement notation of a given +ve/-ve number / integer . Hope that helps .

link

answered 04 Apr '13, 19:07

vineetpaliwal's gravatar image

6★vineetpaliwal
12.4k47107171
accept rate: 12%

It's well described here http://en.wikipedia.org/wiki/Bitwise_operation#NOT

NOT x = −x − 1

link

answered 04 Apr '13, 19:08

betlista's gravatar image

3★betlista ♦♦
16.9k49115225
accept rate: 11%

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×184
×166
×29
×19

question asked: 04 Apr '13, 18:30

question was seen: 1,142 times

last updated: 04 Apr '13, 19:08