dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Home » Tip Bank » C++ » Coding
Language: C++
Expertise: Advanced
Jun 19, 2003

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


Negative Numbers Represented in C++

You probably know that integers are represented in binary--in base 2. This is pretty straightforward for positive numbers, but it means you must choose an encoding for representing negatives. The encoding used by C++ (as well was by C and Java) is two's complement.

In two's complement, the first bit of a negative number is always 1. Otherwise, the number is 0 or postive. To find the bitstring representing a negative number, you take the bitstring representing the corresponding positive number and flip all the bits. Next, add 1 to the result.

In the following example, Ive used 4-bit numbers for simplicity:


  -5d = -(0101b) = (1010b + 1b) = 1011b
Notice that -1d is represented as all 1's:

  -1d = -(0001b) = 1110b + 1 = 1111b
A nice property of this encoding is that you can subtract by negating and then adding the following:

  7d - 3d = 0111b
          - 0011b

  =>        0111b
          + 1100b + 1

  =>        0111b
          + 1101b
          = 0100b = 4d
Yet another nice property is that overflows and underflows wrap around and cancel one another out, like this:

  5d + 6d = 0101b
          + 0110b
          = 1011b
          = -(0100b + 1)
          = -0101b = -5d
If you subtract 6 from this result (by adding its negation), youll get 5 back. First, compute -6:

  -6d = -(0110b) = 1001b + 1 = 1010b
Then, add -6d to -5d to get the original value:

           1011b
         + 1010b
         = 0101
Matthew Johnson
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date