O.4 — Converting between binary and decimal

Consider a normal decimal number, such as 5623. We intuitively understand that these digits mean (5 * 1000) + (6 * 100) + (2 * 10) + (3 * 1). Because there are 10 decimal numbers, the value of each subsequent digit to the left increases by a factor of 10.

Binary numbers work the same way, except because there are only 2 binary digits (0 and 1), the value of each digit increases by a factor of 2. Just like commas are often used to make a large decimal number easy to read (e.g. 1,427,435), we often write binary numbers in groups of 4 bits to make them easier to read (e.g. 1101 0101).

The following table counts to 15 in decimal and binary:

Decimal Value Binary Value
0 0
1 1
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
9 1001
10 1010
11 1011
12 1100
13 1101
14 1110
15 1111

Converting binary to decimal

In the following examples, we assume that we’re dealing with unsigned integers.

Consider the 8 bit (1 byte) binary number 0101 1110. Binary 0101 1110 means (0 * 128) + (1 * 64) + (0 * 32) + (1 * 16) + (1 * 8) + (1 * 4) + (1 * 2) + (0 * 1). If we sum up all of these parts, we get the decimal number 64 + 16 + 8 + 4 + 2 = 94.

Here is the same process in table format. We multiply each binary digit by its digit value (determined by its position). Summing up all these values gives us the total.

Converting 0101 1110 to decimal:

Binary digit 0   1   0   1   1   1   1   0  
* Digit value 128 64 32 16 8 4 2 1
= Total (94) 0 64 0 16 8 4 2 0

Let’s convert 1001 0111 to decimal:

Binary digit 1   0   0   1   0   1   1   1  
* Digit value 128 64 32 16 8 4 2 1
= Total (151) 128 0 0 16 0 4 2 1

1001 0111 binary = 151 in decimal.

This can easily be extended to 16 or 32 bit binary numbers simply by adding more columns. Note that it’s easiest to start on the right end, and work your way left, multiplying the digit value by 2 as you go.

Method 1 for converting decimal to binary

Converting from decimal to binary is a little more tricky, but still pretty straightforward. There are two good methods to do this.

The first method involves continually dividing by 2, and writing down the remainders. The binary number is constructed at the end from the remainders, from the bottom up.

Converting 148 from decimal to binary (using r to denote a remainder):

148 / 2 = 74 r0
74 / 2 = 37 r0
37 / 2 = 18 r1
18 / 2 = 9 r0
9 / 2 = 4 r1
4 / 2 = 2 r0
2 / 2 = 1 r0
1 / 2 = 0 r1

Writing all of the remainders from the bottom up: 1001 0100

148 decimal = 1001 0100 binary.

You can verify this answer by converting the binary back to decimal:

(1 * 128) + (0 * 64) + (0 * 32) + (1 * 16) + (0 * 8) + (1 * 4) + (0 * 2) + (0 * 1) = 148

Method 2 for converting decimal to binary

The second method involves working backwards to figure out what each of the bits must be. This method can be easier with small binary numbers.

Consider the decimal number 148 again. What’s the largest power of 2 that’s smaller than 148? 128, so we’ll start there.

Is 148 >= 128? Yes, so the 128 bit must be 1. 148 - 128 = 20, which means we need to find bits worth 20 more.
Is 20 >= 64? No, so the 64 bit must be 0.
Is 20 >= 32? No, so the 32 bit must be 0.
Is 20 >= 16? Yes, so the 16 bit must be 1. 20 - 16 = 4, which means we need to find bits worth 4 more.

Is 4 >= 8? No, so the 8 bit must be 0.
Is 4 >= 4? Yes, so the 4 bit must be 1. 4 - 4 = 0, which means all the rest of the bits must be 0.

148 = (1 * 128) + (0 * 64) + (0 * 32) + (1 * 16) + (0 * 8) + (1 * 4) + (0 * 2) + (0 * 1) = 1001 0100

In table format:

Binary number 1   0   0   1   0   1   0   0  
* Digit value 128 64 32 16 8 4 2 1
= Total (148) 128 0 0 16 0 4 0 0

Another example

Let’s convert 117 to binary using method 1:

117 / 2 = 58 r1
58 / 2 = 29 r0
29 / 2 = 14 r1
14 / 2 = 7 r0
7 / 2 = 3 r1
3 / 2 = 1 r1
1 / 2 = 0 r1

Constructing the number from the remainders from the bottom up, 117 = 111 0101 binary

And using method 2:

The largest power of 2 less than 117 is 64.

Is 117 >= 64? Yes, so the 64 bit must be 1. 117 - 64 = 53.
Is 53 >= 32? Yes, so the 32 bit must be 1. 53 - 32 = 21.
Is 21 >= 16? Yes, so the 16 bit must be 1. 21 - 16 = 5.

Is 5 >= 8? No, so the 8 bit must be 0.
Is 5 >= 4? Yes, so the 4 bit must be 1. 5 - 4 = 1.
Is 1 >= 2? No, so the 2 bit must be 0.
Is 1 >= 1? Yes, so the 1 bit must be 1.

117 decimal = 111 0101 binary.

Adding in binary

In some cases (we’ll see one in just a moment), it’s useful to be able to add two binary numbers. Adding binary numbers is surprisingly easy (maybe even easier than adding decimal numbers), although it may seem odd at first because you’re not used to it.

Consider two small binary numbers:
0110 (6 in decimal) +
0111 (7 in decimal)

Let’s add these. First, line them up, as we have above. Then, starting from the right and working left, we add each column of digits, just like we do in a decimal number. However, because a binary digit can only be a 0 or a 1, there are only 4 possibilities:

  • 0 + 0 = 0
  • 0 + 1 = 1
  • 1 + 0 = 1
  • 1 + 1 = 0, carry a 1 over to the next column

Let’s do the first column:

0110 (6 in decimal) +
0111 (7 in decimal)

0 + 1 = 1. Easy.

Second column:

0110 (6 in decimal) +
0111 (7 in decimal)

1 + 1 = 0, with a carried one into the next column

Third column:

0110 (6 in decimal) +
0111 (7 in decimal)

This one is a little trickier. Normally, 1 + 1 = 0, with a carried one into the next column. However, we already have a 1 carried from the previous column, so we need to add 1. Thus, we end up with a 1 in this column, with a 1 carried over to the next column

Last column:

0110 (6 in decimal) +
0111 (7 in decimal)

0 + 0 = 0, but there’s a carried 1, so we add 1. 1101 = 13 in decimal.

Now, how do we add 1 to any given binary number (such as 1011 0011)? The same as above, only the bottom number is binary 1.

       1  (carry column)
1011 0011 (original binary number)
0000 0001 (1 in binary)
1011 0100

Signed numbers and two’s complement

In the above examples, we’ve dealt solely with unsigned integers. In this section, we’ll take a look at how signed numbers (which can be negative) are dealt with.

Signed integers are typically stored using a method known as two’s complement. In two’s complement, the leftmost (most significant) bit is used as the sign bit. A 0 sign bit means the number is positive, and a 1 sign bit means the number is negative.

Positive signed numbers are represented in binary just like positive unsigned numbers (with the sign bit set to 0).

Negative signed numbers are represented in binary as the bitwise inverse of the positive number, plus 1.

Converting integers to binary two’s complement

For example, here’s how we represent -5 in binary two’s complement:

First we figure out the binary representation for 5: 0000 0101
Then we invert all of the bits: 1111 1010
Then we add 1: 1111 1011

Converting -76 to binary:

Positive 76 in binary: 0100 1100
Invert all the bits: 1011 0011
Add 1: 1011 0100

Why do we add 1? Consider the number 0. If a negative value was simply represented as the inverse of the positive number, 0 would have two representations: 0000 0000 (positive zero) and 1111 1111 (negative zero). By adding 1, 1111 1111 intentionally overflows and becomes 0000 0000. This prevents 0 from having two representations, and simplifies some of the internal logic needed to do arithmetic with negative numbers.

Converting binary two’s complement to integers

To convert a two’s complement binary number back into decimal, first look at the sign bit.

If the sign bit is 0, just convert the number as shown for unsigned numbers above.

If the sign bit is 1, then we invert the bits, add 1, then convert to decimal, then make that decimal number negative (because the sign bit was originally negative).

For example, to convert 1001 1110 from two’s complement into a decimal number:
Given: 1001 1110
Invert the bits: 0110 0001
Add 1: 0110 0010
Convert to decimal: (0 * 128) + (1 * 64) + (1 * 32) + (0 * 16) + (0 * 8) + (0 * 4) + (1 * 2) + (0 * 1) = 64 + 32 + 2 = 98
Since the original sign bit was negative, the final value is -98.

Why types matter

Consider the binary value 1011 0100. What value does this represent? You’d probably say 180, and if this were a standard unsigned binary number, you’d be right.

However, if this value was stored using two’s complement, it would be -76.

And if the value were encoded some other way, it could be something else entirely.

So how does C++ know whether to print a variable containing binary 1011 0100 as 180 or -76?

In case the section title didn’t give it away, this is where types come into play. The type of the variable determines both how a variable’s value is encoded into binary, and decoded back into a value. So if the variable type was an unsigned integer, it would know that 1011 0100 was standard binary, and should be printed as 180. If the variable was a signed integer, it would know that 1011 0100 was encoded using two’s complement (now guaranteed as of C++20), and should be printed as -76.

What about converting floating point numbers from/to binary?

How floating point numbers get converted from/to binary is quite a bit more complicated, and not something you’re likely to ever need to know. However, if you’re curious, see this site, which does a good job of explaining the topic in detail.

Quiz time

Question #1

Convert 0100 1101 to decimal.

Show Solution

Question #2

Convert 93 to an 8-bit unsigned binary number. Use both methods above.

Show Solution

Question #3

Convert -93 to an 8-bit signed binary number (using two’s complement).

Show Solution

Question #4

Convert 1010 0010 to an unsigned decimal number.

Show Solution

Question #5

Convert 1010 0010 to a signed decimal number (assume two’s complement).

Show Solution

Question #6

Write a program that asks the user to input a number between 0 and 255. Print this number as an 8-bit binary number (of the form #### ####). Don’t use any bitwise operators. Don’t use std::bitset.

Show Hint

Show Hint

Show Solution

6.1 -- Compound statements (blocks)
O.3 -- Bit manipulation with bitwise operators and bit masks

456 comments to O.4 — Converting between binary and decimal

  • Kleidescope

    Thank you for the tutorial. Been following obsessively for a couple days now. It is definitively demystifying the world of programming for me.
    Thought I would throw my solution into the mix as well. I think I over complicated it but it worked just the same.

  • Methos

    So, I tried to use the pow function you mentioned in a previous section and ran into all kinds of problems getting my compiler to be happy with the user value (which I had as an int) and the inputs/outputs of pow (which are floats or doubles seemed to work). Then I glanced at your answer for a hint and realized that the hint should have warned me off going that route.

    I wound up doing the following for the interesting part

    because I was having issues with if statements (I've done some work with VBA recently and got used to writing code of the form if--lots of stuff--endif, but it seems C++ really just wants one thing to do after an if). It didn't occur to me to just write two if statements with repeated conditions for printing the bit and reducing the user value.

    I don't think I saved myself any keystrokes, but it's different so I thought I'd share it.

  • C++ newbie

    i recommend talking about how each digit is the base number raised to the power of 0, then 1, then 2...

    it seemed kind of random how when going right to left in binary, it goes 1, 2, 4, 8, 16
    maybe explain how it's actually just 2^0 (which equals 1), 2^1, 2^2, 2^3, 2^4, etc.

    • Lyle

      Here's an example using that approach and counting down the bit positions from L to R. I adapted it from another poster's code:

  • Todd


    "However, (if) this value was stored using two’s complement, it would be -76."

  • Stamos

    I got it! This is a way to translate a number to binary using the first method:

  • Stamos

    I tried this as an alternative (method 1) but it wont give the correct answer. Can someone tell me why? Thanks!

  • Joseph

    Can someone help me with this? It compiles and works (almost) fine, except that the answer is raised by 1 (the binary answer). I don't know why... and sorry I don't know how to use the code /code thing..

    #include <iostream>

    int solve(int x, int pow)
        int a = (x >= pow) ? 1:0;
        std::cout << a;
        if (x >= pow)
            x -= pow;
        return x;

    int main()
        using namespace std;

        cout << "Choose a number to change it to binary." << endl;
        int x;
        cin >> x;

        solve(x, 128);
        solve(x, 64);
        solve(x, 32);
        solve(x, 16);
        cout << " ";
        solve(x, 8);
        solve(x, 4);
        solve(x, 2);
        solve(x, 1);

        return 0;

    • Snowman

      You were 99.9% of the way there. Remember, the solve function modifies x if it meets the condition x >= pow and returns x. If it does not meet the condition, x is not modified, but it still returns x. All I changed was add "x = " to the 8 calls to solve. I also added a cout << endl for formatting purposes.

      To use the code highlighter, do this:

      (code)just copy and paste code right from file into here(/code) (replace round brackets with square)

      Anyway, your code with the small change:

  • Joseph

    Am I the only one using this tutorial...?...
    I'm loving it and am learning so much and so quickly. Although I think at this point I'm still in the more general programming stuff, I have yet to get to the difficult C++ stuff like pointers and all that lol.
    Great tutorial, thank you.

    Also, I was wondering. By the time I finish this tutorial (and let's say that I completely understand and can implement everything mentioned and taught) would I know enough C++ to actually start building applications and games that are more worthwhile? Number-guessing games aren't exactly in my top-10 of favorite games haha.

    Oh and one more thing. I look at the comments and see all these complicated codes that I only have understand. Mine seem much simpler and don't have as much fancy stuff. Are they just more advanced or am I just slow haha.

    • Snowman

      Hey man.

      First off, I'm also going through this tutorial at the moment (4.3a currently)

      Once you are done with this tutorial, you will know how to use the C++ language very efficiently and understand a lot of what it has to offer. Unfortunately though you will still be a while off making games and applications, especially if you have no prior programming experience. The programming gods out there have utilized the language to create some code that will probably make your eyes bleed just looking at it, never mind trying to understand it. You will have to use that code to create apps or games. It may take a while to reach that point, but never feel discouraged and keep pushing, learning and practicing. The best way to learn how to reach god level is to get on Github and start reading other peoples' code. If you find a project you like, start tearing through it. You will learn one hell of a lot just by reading other peoples' code. Coding games is also very complex and platform dependent, for example an Android game will be made with Java usually, not C++ (if I am not mistaken).

      As for the complexity of some of the code posted, don't be stressed. Some, if not most, people here (me included) have some prior programming knowledge. C++ is probably one of the most difficult wide-use languages out there, so people start smaller. I learnt Delphi 7 in high school and have just applied to varsity to study software engineering, I decided to learn C++ before I start in a few months. Some of the code looks like Chinese because the tutorial, at this point, has not yet covered the topic (such as for loops). If you are able to answer the quizzes with similar code as the provided answers, it means you understand the intended lesson and you should be proud. If you don't get it right, keep practicing =).

      Learning to program is a very long shot from easy, no one expects you to be a pro tomorrow. Keep at it. My suggestion is go through a chapter (3.1 - 3.x for example) then go through it again before moving on to the next. It is a lot of information and sometimes some can be lost or new information in a later lesson can help you understand a previous lesson better.

      • Joseph

        Ah the most inspirational reply ever. Thank you haha. and it's good to know I'm not the only one using this tutorial 7+ years late hahah

  • Snowman

    Alex, you are truly awesome! I just want to say thank you so much for these! I know it will get harder (which I am looking forward too) but the amount of detail you use as well as the way you explain each topic is very clear and precise. I searched for a couple days for C++ tutorials (textbooks, YouTube then websites) and have stuck with your site and plan on seeing it through. Again, thank you so much!

    Here's my solution for the sake of adding it:

  • Tony

    I managed to get a working answer, it compiles, and it runs, and it works correctly, however the compiler gives me a warning and I'm not sure why.

    The error is: (27): warning C4244: '=' : conversion from 'double' to 'int', possible loss of data

    So far as I can tell I used ints and no double so not sure why it's throwing that up, any help/advice appreciated.

    • Alex

      The issue is coming from this line:

      The pow() function returns a double. So, looking at types, you've essentially said "int = (int - double)", which resolves to "int = double". The compiler is warning you that the double value could be truncated.

      Given that you're always taking a power of 2, this will never be a real problem, but the compiler isn't smart enough to detect this.

      You can get rid of the warning by using a static cast to tell the compiler you know that you're converting a double to an int:

  • Jana

    Hi Alex,

    Thanks for the tutorials, they are very well thought through.

    I am a bit puzzled about the inverting all the bits into the opposite value. Why is this done? Am I right thinking it is only done for signed numbers?



    (PS: There is an error in:

    "Let’s convert 117 to binary using method 1:

    117 / 2 = 58 r1
    58 / 2 = 29 r0
    29 / 2 = 14 r1
    14 / 2 = 7 r1 this line should say: 14 / 2 = 7 r0
    7 / 2 = 3 r1
    3 / 2 = 1 r1
    1 / 2 = 0 r1

    Constructing the number from the remainders from the bottom up, 117 = 111 1101 binary" (this should be 111 0101)
    Method 2 gives the correct answer.)

    • Alex

      Thanks for catching the error.

      Using two's complement, negative signed numbers are stored as the inverse of the positive number, plus 1. Positive signed numbers use the same representation as unsigned numbers.

      As for why we do this, we do this because it makes the math work out nicely, and allows us to add both positive and negative numbers without having to do anything special.

      Consider: Any binary number plus its inverse is 1111. If we add 1, we get 0000 (due to overflow). So, by arbitrarily deciding that the binary representation for a negative number should be the inverse of the positive plus 1, we guarantee that that any positive signed number plus its negative signed number will equal binary 0. As it should!

  • Metereo_Rex

    I think it's worth noting that the process behind subtracting 1 from binary numbers is not very clear.

    I've figured it out, but it still managed to leave me puzzled for a short while.

  • Amit Sharma

    I tried Solving the problem this way.
    i think it works good.Just needed some feedback if its good or does it need some attention to any bad habits i might have incurred.

  • Noether

    Hi there
    thought I would share my attempt at this for others and to get feedback.

    I had to look up arrays but that was the only new concept here, it was the only way I could think of to reverse the order of the bits. However doing it this way has the benefit that it can easily be extended to work for any positive number.
    Thanks for these awesome tutorials!

    • Noether

      There was a typo on line 23, -index should be -–index. not sure how that happened as I copy pasted from codeblocks and it was correct there. The correct code should be

      while (index != 0) //While loop to reverse the order of the bits
      -–index; // there was a typo here
      cout << arr[index];
      return 0;

      I’m not sure if I’m doing these code html tags correctly ethier, if it doesn’t work properly this time can someone help me out?

      Edit: it seems that a double "-" simply gets coverted to a single one, not sure why that is.

    • Paulo Ribas

      Thank you for your help.I was looking for something that implement stack with vector for decimal to binary conversion.

  • Stefan

    Hi Alex,
    I discovered a little mistake in the answer of quiz question No. 6:
    Instead of if (x > pow), the if-statements should be if (x >= pow). If the power of 2 is equal to the number, we should set the according bit to 1 (and substract).


  • RT

    the representation of -76 is coinciding with the one of 180.So,how to differentiate?


    • Alex

      You can't differentiate just by looking at the binary representation. You have to know how to interpret the representation (this is why variables have types). If 10110100 is an unsigned number, then it means 180. If it is a signed number, it means -76.

      Assuming we're talking about an 8-bit number, you'll notice that both signed and unsigned numbers have the same binary representation for 0 - 127 (the first 7 bits). However, after that point, the meanings diverge. 1000 0000 is 128 unsigned, but -128 signed. Every additional bit adds 1 to both signed and unsigned numbers.

      Or, another way to think about it:
      Unsigned: 1011 0100 = 1000 0000 + 0011 0100 = 128 + 52 = 180 unsigned
      Signed: 1011 0100 = 1000 0000 + 0011 0100 = -128 + 52 = -76 signed

  • RP

    To convert Decimal number to Binary easy method is to divide the decimal number by two just like LCM method and write the remainder (1 and 0) from bottom i.e from last remainder.

  • devin

    i figured out an another way to make a decimal --> binary converter :

    for (int i=7; i>0; i--){ (a >= pow(2,i)) ? a -= pow(2,i) + ++b * 0 : 0;b *= 10;}
    b += a;

    a : decimal number
    b : binary result

  • dice3000

    I didn't know that negative binary numbers use overflow :/

  • Mindstormscreator


    I just want to say these are the best C++ (maybe even programming tutorials) I have ever come across, including books. The way you organize these tutorials combined with contributions from these comment sections put together some really impressive stuff. Thanks so much!

    -Alex (haha)

  • zkn1729

    There is one thing I'm not getting here. I assume our variable is signed int x=180; It will be stored as 1011 0100. When our program calls x to print to console, how does program decide which one (180 or -76) will be printed to console? (1011 0100 = -76 and 1011 0100 = 180)

  • Wait, so the smallest negative binary number (signed) is 127, or am I missing something?

  • PReinie

    There are 10 kinds of people in this world...

    Those who know binary, and those who don't.

    (I didn't make this one up but it's great!)


  • Koi

    So I tried to create a program to convert a decimal number into a binary number based on your thoughts. It doesn't seem to work for some reason. Here it is:

    what's up with it?

    • aakash_cracker

      i didn't understood the use of npower is declared only not defined..
      thanks koi

      • Lyle

        There is no ^ exponent operator in C++.

        and use the pow(base,power) function from it.

        In this case he'd have been close had he replaced the (2^nPower) instances with for instance:

  • Gio

    For all Windows users, the default "Calculator" application can help with conversion: Change the mode to scientific, then, enter the decimal number, then hit "Bin" to convert to binary. Also works in reverse and with Hexadecimal and Octal.

  • Alfreda

    I found a website where you could buy doormats with the word "Welcome" printed on them in binary.

    I'm guessing it just took the ASCII code for each letter in "Welcome" and converted those numbers to binary, which turns out to be "01110111011001010110110001100011011011110110110101100101"

    which was four rows of numbers on the doormat :P

    The caption said "Welcome your friends & family into your hi-tech culture!


  • Morgan

    There's one thing I'm not quite getting here. Let's take the last example for instance.

    -76 in binary is 1011 0100


    180 in binary is also 1011 0100

    how do you determine which one is which? Or am I right in assuming that this is why there is a need for signed and unsigned?

    • You are correct that 1011 0100 is both -76 and 180. As you surmise, which value you actually get is determined by whether your variable is signed or unsigned. If your variable is signed, you will get -76. If it's unsigned, you'll get 180.

  • Jeffey

    as a practice on further learning how to write code. I made this program that converts decimal to binary. It uses the same technique as the tutorial shows. I mainly did this because most the programs I have made have had a guideline to it. This one I made up all on my own and it is effective for decimal 0-255. I plan on expanding it further include bigger numbers.

    #include "stdafx.h"
    #include <iostream>
    int main();

    void DecToBin(int y)
    using namespace std;
    for(int x = 256; x /= 2;)
    if(y >= x)
    (cout << "1") && (y -= x);
    cout << "0";
    cout << "nn";

    int main()
    using namespace std;
    cout << "enter a number: ";
    int y;
    cin >> y;
    return 0;

  • Abhishek

    Thanks!!Thats a good revision of what i had learnt in school 3 yrs ago......

    But I prefer this method for decimal to binary conversion::
    Short division by two with remainder

    This method is much easier to understand when visualized on paper. It relies only on division by two.

    1. For this example, let's convert the decimal number 156 to binary. Write the decimal number as the dividend inside an upside-down "long division" symbol. Write the base of the destination system (in our case, "2" for binary) as the divisor outside the curve of the division symbol.

    2. Write the integer answer (quotient) under the long division symbol, and write the reminader (0 or 1) to the right of the dividend.

    2)156 0
    3. Continue downwards, dividing each new quotient by two and writing the remainders to the right of each dividend. Stop when the quotient is 1.

    2)156 0
    2)78 0
    2)39 1
    2)19 1
    2)9 1
    2)4 0
    2)2 0
    4. Starting with the bottom 1, read the sequence of 1's and 0's upwards to the top. You should have 10011100. This is the binary equivalent of the decimal number 156.


    • That's definitely a faster way to do it in practice. An even faster way is to use windows calculator (or another program). ;)

      (To use windows calculator in this manner, go to the View menu and choose "scientific" -- then you can access the Dec and Bin buttons, which are decimal and binary).

      The wordpress spam filter does a really good job of catching stuff, but it occasionally gets false positives. I restored the version of your article that it marked as spam and told it that it wasn't spam. It's supposed to learn from past behavior, so hopefully next time it will be smarter about how to treat wikihow links.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]