• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4361
  • Last Modified:

Function to calculate two's complement of a number in C++

I am new to C++ and would like sample code on how to create two's complement of a number.
  • 3
1 Solution
have a look at this article to find out what the two's complement is and what it is used for http://en.wikipedia.org/wiki/Two's_complement

int number = 12345; // whatever you like
int twoscompl = ~number + 1; // this is the way as it is defined (negate all bits and add 1)
int twoscompl = -number;  // this is the trivial way to do the same thing in any programming language
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now