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

Posted on 2006-04-01
Last Modified: 2011-10-03
I am new to C++ and would like sample code on how to create two's complement of a number.
Question by:HariniMadugula
    LVL 11

    Accepted Solution

    have a look at this article to find out what the two's complement is and what it is used for'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
    LVL 11

    Expert Comment

    LVL 11

    Expert Comment


    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Join & Write a Comment

    Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
    Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
    The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
    The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

    746 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now