Search

3.7 — Converting between binary and decimal

In order to understand the bit manipulation operators, it is first necessary to understand how integers are represented in binary. We talked a little bit about this in section 2.4 -- Integers, and will expand upon it here.

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 digit increases by a factor of 10.

Binary numbers work the same way, except because there are only 2 binary numbers (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).

As a reminder, in binary, we count from 0 to 15 like this:

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. 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)
----
   1

0 + 1 = 1. Easy.

Second column:

 1
0110 (6 in decimal) +
0111 (7 in decimal)
----
  01

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

Third column:

11
0110 (6 in decimal) +
0111 (7 in decimal)
----
 101

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:

11
0110 (6 in decimal) +
0111 (7 in decimal)
----
1101

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 stored just like positive unsigned numbers (with the sign bit set to 0).

Negative signed numbers are stored as the inverse of the positive number, plus 1. For example, here’s how we convert -5 to 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.

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 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?

Way back in section 2.1 -- Basic addressing and variable declaration, we said, “When you assign a value to a data type, the the compiler and CPU takes care of the details of encoding your value into the appropriate sequence of bits for that data type. When you ask for your value back, your number is “reconstituted” from the sequence of bits in memory.”

So the answer is: it uses the type of the variable to convert the underlying binary representation back into the expected form. 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 (assuming that’s what it was using), and should be printed as -76.

Quiz

1) Convert 0100 1101 to decimal.
2) Convert 93 to an 8-bit unsigned binary number.
3) Convert -93 to an 8-bit signed binary number (using two’s complement).
4) Convert 1010 0010 to an unsigned decimal number.
5) Convert 1010 0010 to a signed decimal number (assume two’s complement).

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.

Hint: Use method 2. Assume the largest power of 2 is 128.
Hint: Write a function to test whether your input number is greater than some power of 2. If so, print ‘1’ and return your number minus the power of 2.

Quiz answers

1) Show Solution

2) Show Solution

3) Show Solution

4) Show Solution

5) Show Solution

6) Show Solution

3.8 -- Bitwise operators
Index
3.6 -- Logical operators

183 comments to 3.7 — Converting between binary and decimal

  • 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)156
    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
    78
    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
    1
    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.

    source:
    http://www.wikihow.com/Convert-from-Decimal-to-Binary

    • 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.

  • 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.

    Code
    #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);
    else
    cout << "0";
    cout << "nn";
    main();
    }

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

  • 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

    but…

    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.

  • 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 😛

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

    Lol.

  • 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.

  • 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 ….it 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:

  • 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!)

    Phil

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

  • 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)

  • Mindstormscreator

    Alex,

    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)

  • dice3000

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

  • 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

  • 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.

  • RT

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

    10110100

    • 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

  • 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).

    Cheers
    Stefan

  • 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.

  • 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.

  • 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.

  • 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?

    Thanks.

    Jana

    (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!

  • 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:

  • 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:

  • 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

  • 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:

  • Stamos

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

  • Stamos

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

  • Todd

    Typo.

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

  • 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:

  • 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.

  • 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.

    • Eberus

      umm…your code….method 2 says you do it with the highest power of 2 but less than the input…
      but your code…. if for example i enter 21, it still uses 128 printing 0001 0101 rather than 1010 1000

  • Edward

    Any caveat using braces in your if statement within your function in Quiz 6 to simplify it?

    int printAndDecrementBit(int x, int pow)
    {
        // Test whether x is greater than some power of 2 and print the bit
        if (x >= pow)
        {
            std::cout << "1";
            return x - pow; // If x is greater than power of 2, subtract the power of 2
        }
        else
        {
            std::cout << "0";
            return x;       // If x is not greater than power 2, just return the value as it is
        }

    • Alex

      No, it’s not only fine, it’s better.

      I didn’t do it that way because we haven’t really talked about if statements or blocks very much yet. We get to those in more detail next chapter.

  • Smokeycow

    There appears to be a word switch error. Method 2 should say "Decimal to binary", not vice-versa as it currently states.

  • andy mackay

    This is how I did it, I was too lazy to include the formatting, so it just print the binary in one long line.

  • piloutik

    Hi,

    #include<iostream>

    int main()
    {
        
        signed int x = 0b10110100;
        std::cout<<x;
        return 0;
    }

    This prints 180 . x is a signed integer so it should print -76, shouldn’t it ? I’m confused 🙁

    • Alex

      Binary literals are always treated as unsigned.

      The following two statements are equivalent:

      In the first statement, x1 clearly gets assigned 180. In the second one, the same thing happens, though it’s not quite so obvious.

      It makes sense to me that binary literals wouldn’t support negative numbers, because C++ doesn’t define what the underlying representation for negative numbers should be. In the above, you’re assuming two’s complement, but it could be something else.

  • person

    In solution 2 you say that the answer is the 1’s and 0’s read from the bottom up, but in the example above that where you converted the decimal 148 into binary (the second method) the answer was read from the top to the bottom. Why?

    I arrived at the conclusion that 93 = 1011 1010 because I thought that the answer should be read from the top down.

    • Alex

      You’re confusing method 1 and 2. In solution 2, I show both methods. Using method 1, we get the answer bottom up. Using method 2, we get the answer top down.

  • Amandeep

    Alex,
    For the Quiz question number 6, you used method 2 to write the code, but I always use method 1 to convert decimal to binary, so I wanted to use method 1 to write the code. This is what I wrote and it works fine EXCEPT that it prints the digits in reverse order because that is how we calculate the bits in method 1 (the right most bit is calculated first). Can you suggest something to fix my code and make it print right to left? Or something else? Or the only way to achieve this is method 2 because it starts calculating bits from left? Here is my code:
    #include <iostream>
    int calculateBit(int x) {
        using namespace std;
        if ((x%2) == 1)
            cout << "1";
        else
            cout << "0";
        return 0;
    }

    int main() {
        using namespace std;
        cout << "Enter a number between 0 and 255" << endl;
        int decimalNumber;
        cin >> decimalNumber;
        int x = decimalNumber;
        calculateBit(x);
        x = (x/2);
        calculateBit(x);
        x = (x/2);
        calculateBit(x);
        x = (x/2);
        calculateBit(x);
        x = (x/2);
        calculateBit(x);
        x = (x/2);
        calculateBit(x);
        x = (x/2);
        calculateBit(x);
        x = (x/2);
        calculateBit(x);
        return 0;
    }

    //IT IS WORKING OK BUT PRINTS DIGITS IN REVERSE ORDER SINCE I AM CALCULATING THE RIGHT MOST BIT FIRST AND PRINTING IT.

    • Alex

      You’ve discovered the challenge with using method #1. There are plenty of ways to work around this, but we haven’t covered any of them yet.

      Probably the easiest way would to use a std::string to collect all of the bits as you calculate them, and then print the string at the end of your program. We cover std::string in lesson 4.4b -- An introduction to std::string. To have your bits print in the correct order, you’ll need to append the bit you just calculated to the front of the string, not the end.

  • Amandeep

    Thanks Alex, will wait to get there. I did see another commentator above, "Stamos" write a program using method 1 by assigning each output to a new integer variable and then print all the integers in reverse order. I think it would work  but it is not appealing because it does not use function and main looks like doing repetitive work. Thanks again for all the help!

  • hbl

    Hi Alex thanks for the great tutorials.This is my solution what you think about that ? and what you suggest.

  • spencer lewis

    I was trying to make a larger 16 bit decToBin converter and I get an alert from compiler that says:
    "Warning    C4244    ‘return’: conversion from ‘double’ to ‘int’, possible loss of data 12".

    it says it is line 12 and 14 I looked but I couldn’t find anything to fix it.
    plz help:)

  • spencer lewis

    there is still data loss:(
    it prints:
    0000 0000 0000 0001 for 1
    0000 0000 0000 0011 for 2-3
    0000 0000 0000 0111 for 4-7
    0000 0000 0000 1111 for 8-15
    0000 0000 0001 1111 for 16-31
    0000 0000 0011 1111 for 32-63
    0000 0000 0111 1111 for 64-127
    0000 0000 1111 1111 for 128-255
    and so on

  • caboose

    I am trying to make it so I didn’t have to run the individual binary places and have the cpp do it for me I got the code but after I enter the number it gets frozen I don’t know what is going on.
    here it is:

    • spencer lewis

      I don’t know how to explain it but your set up, when it works will only print ones, from what I understand when going to run the number 5 it will print 11 not 101, it skips over the 0 part because when it gets the x it is going from the bottom instead of incrementing down from the highest 2 power.
      so for 56 it will find 32. (witch is a pretty cool idea) then it will subtract: 56-32=24
      it will keep going
      24 -> 16
      24-16=8
      8 -> 8
      since it has no I guess way to get a 0 it will write 111 instead of 1110000

  • spencer lewis

    try this:

  • caboose

    thank you but I still have the problem of it not writing and freezing

  • Sam

    Hi, I am wondering how the ‘add 1’ part works? I understand everything else and its very well written but I am really puzzled as to HOW you do this and why 1011 0011 becomes       1011 0100? could I trouble someone to maybe explain me through it?

    Converting -76 to binary:

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

    • Alex

      It works just like normal math. For simplicity of explanation, let’s remove the left 4 bits (since they don’t change).

      Start with 0011 + 1:

      0011
      0001
      ---
      0, carry the 1 (in base 10 math, this is the same as how 9 + 1 = 0 carry the 1)

      1
      0011
      0001
      ---
      0, carry the 1

      1
      0011
      0001
      ---
      1

      0011
      0001
      ---
      0

      So 0011 + 1 = 0100.

      Make sense?

  • Nemesh

    i tried using what i learned in the lesson to make binary to decimal code and here is what i came out with:

  • Cody

    This is an example of using method #1 for converting decimal to binary (for positive decimal number). Now the function reverseString(std::string text) probably wasn’t necessary because I’m quite positive there already exists a standard function that allows the ability to return a mirrored string. This was a great exercise Alex!

  • Morten

    Also felt like sharing my answer. Like so many others, I’m learning a lot from your tutorials! Thank you 🙂

    Like others I also came across the warning using int’s in pow. However, I simply casting using (int), is that acceptable code?

    And my answer to question 6.

    • Alex

      (int) is a C-style cast. In C++, you should use static_cast() instead. If you need to convert a double to an int, this is the best way to do it, as it makes it explicit that the conversion is intentional.

  • Amit

    I have two questions. 🙂
    As you said, when a variable is stored within the memory as bits, the computer saves it’s type and takes care of converting the bits into the correct number.
    1. What do you mean by the computer? the CPU?
    2. How does the computer saves the variable’s type? in a seperate memory section?
    I know it is probably beyond the scope of this section but i am very curious.
    Thanks!

    • Alex

      1) The compiler and the CPU. CPU have instructions for dealing with many fundamental data types. The compiler can also handle conversions that the CPU can’t.
      2) The compiler builds and maintains a table of all the symbols seen in a program, called a symbol table. This typically includes a symbol’s name, type, and scope.

      • Amit

        But what happens when the file already is executable?
        Btw - Thank you very much, Im very glad i found this tutorial!
        Thanks for everything!

        • Alex

          I’m not sure what you mean. When the program is compiled into an executable, the compiler turns your code into CPU instructions that do the conversions. Or if the CPU doesn’t offer direct support, it can mimic this via built-in functions to do conversions.

          Thus, when you run your program, you’re running code that is already leveraging this capability.

          • Amit

            I mean, how is the compiler manifested when the program is already executable?
            Doesnt it have know in advance where the free memory will be?
            I guess what i don’t understand is - When the file is executable, is there a link to the compiler when running it? or i can run it on every computer i want (even if the computer doesn’t have c++ compiler)?

            • Alex

              Once the program is compiled, the compiler’s role is finished. However, when the compiler is compiling your program, it can “compile in” other code that it needs. This could include code to convert one type to another, or other helper tools.

              Once the program is an executable, you should be able to run it on every computer running the same OS and architecture the program was compiled for (with a small caveat for programs that link to the C++ runtime library dynamically -- for those, the C++ runtime library must also be installed on the machine).

  • T2theOm

    I made the same thing for ternary numbers. Do you think this is well written, Alex? What would you improve?

    #include <iostream>

    int printAndDecrementBit(int a, int pow)
    {
        using namespace std;
        if (a>=2*pow)
            cout << "2";
        else if (a>=pow)
            cout << "1";
        else
            cout << "0";
        if (a>=2*pow)
            return a - 2*pow;
        else if (a>=pow)
            return a-pow;
        else
            return a;                    
    }

    int main()
    {
        using namespace std;
        cout << "Type in a number from 0 to 80.  " << endl;
        
        int x;
        cin >> x;
        
        x=printAndDecrementBit(x, 27);
        x=printAndDecrementBit(x, 9);
        x=printAndDecrementBit(x, 3);
        x=printAndDecrementBit(x, 1);
        
        return 0;
    }

    • Alex

      Yes.

      Here’s what I’d improve:
      1) I’d add comments to printAndDecrementBit to make it easier to follow the logic.
      2) I’d add error checking around the user input in case they enter a number that is not between 0 and 80.

      But other than that, it looks good.

  • Jim

    Alex,
    I’m still a little bit confused about converting signed negative numbers to binary and vice versa.

    Lets see if I understand binary. (8 bit) If the left most bit is a one the number has to be negative, unless all the bits are ones. Which makes this 1111 1111 would be 255.  Is this true?

    Therefore if you see this 1000 0101. I know right away that this has to be a negative number. Since the left most bit is a one and all the other bit differ. (Not all ones) I this true?

    To convert 1000 0101 to a negative decimal, I now subtract one to give me this 1000 0100 then I invert it to this 0111 1011 and the decimal is -123.  Is this true?

    FYI: Windows 7 and 8 now have a programmer calculator (PC)to convert values.  The scientific calculator no longer has the bin and dec keys. But the new (PC) has very poor instructions. So it’s not easy to figure out how it works.
    You may want to look at it since it uses (and, or ,not).  This may be useful in future lessons.

    • Alex

      > If the left most bit is a one the number has to be negative, unless all the bits are ones.

      A left bit of 1 only indicates a negative number if the binary number is being represented using two’s complement. This is why data type matters, it tells you how to interpret the bits. Normally, if a data type for binary isn’t provided, unsigned integer is assumed.

      If we assume unsigned integer, then 1111 1111 = 255. But if we assume two’s complement, then 1111 1111 = (subtract 1) 1111 1110 and flip the bits = 0000 0001 = -1.

      > To convert 1000 0101 to a negative decimal, I now subtract one to give me this 1000 0100 then I invert it to this 0111 1011 and the decimal is -123. Is this true?

      Yes, that is correct.

  • saurabh sharma

    my answer of question 6 for n bit representation

  • Jim

    Alex,

    Warning Windows 7 and 8 come with a Windows programmers calculator. This calculator does not come with instructions on how to use it, so you may get unexpected results.

    I tried to convert binary to decimal and vice versa and I got the wrong results a couple of times. This was probably due to an error on the way I did my entries.

    It would help if Windows provided some good instructions.

    • Alex

      Unfortunately there isn’t much I can do about this. 🙁

      • Jim

        Alex,

        After working with the Windows 7 programmers calculator for a while I finally got it to work properly every time.

        The problem is you can not enter a negative number when you are in decimal (dec) mode. There is no button to switch a positive number to a negative. However you can enter a negative number in between parentheses(-76)then it works.
        Note:(The numbers do not turn negative until you place the closing parentheses.)

        If you enter the two’s compliment bits for a negative number (signed integer)when you are in bin mode. It gives you the right conversion every time

  • Tim

    Dear Alex, below is my code for the last assignment:

    However, when I test it, with number 14 for example, it prints 0000 1111 instead of 0000 1110. I know that there’s some mistake but I couldn’t figure it out, please help me. 🙁

  • Dngallar

    How I can improve my code?

    Thanks!!

  • Arda

    Mine is a bit different.

  • Nortski

    My alternative answer to question 6. It only uses one call to the function and doesn’t return and value.

  • Sol

    I always don’t understand part of the question when you’re asking us to write a program. I only understand the make this but not the use this. It just doesn’t come to mind. I’m wondering if I’ll ever be a good programmer lol. Anyways, here’s my answer to number 6.

  • Heres my code for singed-unsigned decimal to binary converter…I dont know how the decimals are stored…The concept of float is still floaty lol.I am not convinced by the method used to compare two float values…
    [code]
    #define DIGITS 8                             //Change to increase Number of digits
    #include <iostream>
    using namespace std;
    int main()
    {
        int a(0),b[DIGITS],c(DIGITS);
        bool e(0),f(0);
        cout<<"Enter a number";
        for(a=0;a<DIGITS;a++)                   //Initialization of Array b
        {
            b[a]=0;
        }
        cin>>a;
        cout<<"The binary for "<<a<<" is a";
        if(a<0)                                //Check sign of Number
        {
            e=1;                               //Positive negative Check
            a=-a;
        }
        for(a;a>0;a=a/2)                       //Get unsigned Binary Number
        {
             //Checks if the binary number exceeds DIGIT limit.If no then it will continue to convert remaining //decimal into BINARY
            if(c>0)
            {
            c-;
            b[c]=a%2;
            }

            //Checks if the binary number exceeds DIGIT limit.If yes then it will abort all the other pending //process and ask to increase DIGIT limit
            else
                f=1;
        }
        if(e==1)                               //This will 2’s compliment only if the number was negative
        {
            for(a=0;a<DIGITS;a++)
        {
            if(f==1)                           //If Number exceeds digit limit break loop
                break;
            if(b[a]==0)                        //1s compliment each of the number in the array
                b[a]=1;
            else if(b[a]==1)
                b[a]=0;
        }
        b[DIGITS-1]++;                         //Convert 1s Compliment to twos compliment
            for(a=DIGITS-1;a>-1;a-)
            {
                if(f>0||b[a]!=2)               //If Number exceeds digit limit break loop
                break;
                if(b[a]==2&&b[0]!=2)           //Checks if there is any presence of twos in the array to                                                                  //carryout the carry procedure
                {
                    b[a]=0;                    //Makes twos into zeros
                    ++b[a-1];                  //Carries the one after making the two into zero.
                }
            }
        }
        for(a=0;a<DIGITS;a++)                 //Prints the array
        {
            if(f==1)                          //If Number exceeds digit limit break loop
                break;
            cout<<b[a];
        }
        if(e==1)                              //Tells if the binary digit is Negative
            cout<<" Negative";
        if(f==1)                              //Sends error message
        cout<<"/nOverflow Increase the number of DIGITS..NaNa";
         return 0;
    }
    [code]
    Thanx

  • Simon

    My version of the program, can convert positive and negative to binary. I wonder if i could make it simpler.

  • Soul

    This was my own code, though yours is much clearer and far less painstaking.

    Plus you mentioned using a function, I didn’t know how to do all this with just one function until after I saw your example. I really do need to learn to think with functions.

  • Chang

    Many have asked about 1011 0100. How the system can different between 180 and -76 depending on whether its signed or unsigned integer defined.

    So you mentioned earlier that when signed, it will be -76, and when unsigned, it will be 180.

    Still do not quite get it. If under signed declarations, 1011 0100 is -76, then what is 180 in signed binary form?

    • Alex

      There is no 180 in 8 bit signed binary form. The range of an 8 bit signed integer goes from -128 to +127.

      If you want to represent 180 as a signed number, you’ll have to use a 16-bit (or larger) signed integer. And that number would be: 0000 0000 1011 0100.

      So perhaps I haven’t been clear enough:
      1011 0100 is -76 in 8-bit signed
      0000 0000 1011 0100 is 180 in 16-bit signed

      Interesting, isn’t it?

  • Ank

    Hey alex i too wrote the same programme for decimal     to binary converter,but everytime the compiler takes the same value of x which it takes from the user as input.
    For eg. if i took x=67
    The printandDecrementBit() function is called for pow=128 and the o/p on screen obtained is 0.
    After that printandDecrementBit() function for pow=64 is called and o/p on screen obtained is=1.
    Now for the third time when printandDecrementBit() function is called for pow =32,the value that should be substituted in x should be x-pow, but this is not happening instead the value remains 67(i checked it through watch command in debug mode),why is this happening?

  • Elpidius

    Hi Alex, above you wrote "To convert a two’s complement binary number back into decimal, just reverse the process: subtract 1, then invert the bits, then convert to decimal as a standard binary number."

    There’s another (IMO easier) way to convert a two’s complement number into its positive counterpart, just invert the bits, then add 1; instead of subtracting 1, then inverting all the bits.

    It’s just another way and I thought I should mention it, as adding 1 to a binary number is easier than subtracting 1.

    Reference:
    https://en.m.wikipedia.org/wiki/Two%27s_complement

  • Laszlo Janos

    You say that:"To convert a two’s complement binary number back into decimal, just reverse the process: invert the bits, add 1, then convert to decimal as a standard binary number. If the leftmost binary digit in the original binary number is 1, the decimal number is negative."

    When you convert from two’s complement back into decimal, if the binary representation starts with a 0 then you don’t have to flip the binary representation and add 1, you convert to decimal as it is. You only flip and add 1 if the representation in two’s complement has the most significant bit on 1.
    for example here is a representation of a binary number in two’s complement: 0000 0010(2 in decimal) since it starts with 0 you don’t have to flip and add 1, only if it started with 1(for instance 1000 0010 = -126 in decimal) then you need to flip and add 1.

    I think you should correct that!

  • Plurple

    after spending a couple of hours working on making my code work by looking up arrays and dynamic allocating arrays my code works for any size number inputted by the user that is an integer thought I would see what anyone thinks 🙂 if anyone has any comments to improve and each time

    it is a different .cpp file

  • Andy

    Hello Alex, I managed to complete the assignment, albeit using a different code to the one provided in the answer sheet.

    I would like to know if this method of writing is inferior in terms of performance to yours:

    • Andy

      I just realised my binaryValue function had a gross, gross mistake in the x variable decrements.
      I have fixed it now here (rest of the program stays the same):

    • Alex

      This seems generally fine. The only caveat is that it doesn’t extend quite as well for larger numbers (e.g. if you wanted to update this to work with 16-bit numbers instead of 8-bit numbers).

  • J3ANP3T3R

    hmm.. a little confused here ..

    (this part i got .. add 1)

    "Then we invert all of the bits: 1111 1010
    Then we add 1: 1111 1011"

    (but then this adds 99… )
    "Invert all the bits: 1011 0011
    Add 1: 1011 0100"

    looking at the table i take it "add 1" means the next one in table ? how do i add 1 to 1011 0011 without looking at the table ?

    • Alex

      In decimal math, there are ten values: 0 through 9. As soon as we add 1 to 9, the digit rolls over to 0, and we carry a 1 to the next column.
      In binary math, there are only two values: 0 and 1. As soon as we add 1 to 1, the digit rolls over to 0, and we carry a 1 to the next column.

      So, 1011 0011 + 1 -- first we add 1+1 (rightmost column). This is 0, carry 1. That carried 1 gets added to 1 (second rightmost column), producing another 0, and carrying another 1. That carried 1 gets added to 0 (third rightmost column) to produce a 1, and we’re done.

      So 1011 0011 = 1011 0100.

      We can do this a different way. Taking just the last 4 digits: 0011 binary is 3 in decimal. 3 + 1 = 4. 4 in binary is 0100. So we can say 0011 + 1 = 0100.

      • J3ANP3T3R

        nice ! thanks that will help me quickly add binaries without the table.

      • bily salazar

        Hi Alex,

        i am *slowly* teaching myself C++ from scratch using your tutorials & got hung up on this part.  Could you possibly explain the ‘add 1’ & binary addition prior to this lesson or have a link to explain it… took me a good day to figure out how ‘add 1’ worked.  it seems this tutorial assumes we know how to do binary addition.

        thanks,
        b.

        ps.  these tutorials are wonderful!

        • Alex

          I added a section to the lesson talking about how to add binary numbers. Have a read, and let me know if it’s sufficiently clear or whether it needs additional massaging.

          Thanks!

  • J3ANP3T3R

    i’m a little lost here .. in the example above it represented the binary of 5 (0101) as 0000 0101

    does this mean we pad the binary up to 8 digits ? for me this is important to know because if 0 means positive and 1 means negative then the left most digit defines whether it is positive or negative … what if we use the binary representation of 8 which is 1000 ? im confused .. how did we get 0000 0101 from 5 (0101)?

    • Alex

      Usually when we talk about binary, we generally assume we’re talking about positive binary numbers unless specified otherwise.

      For positive binary numbers, we can left-pad them with 0s to our heart’s delight. Similar to how 00000633 is equivalent to 633, 0000 0101 is equivalent to 0101 (which is equivalent to 101).

      Once we bring two’s complement into the picture, things get a little more complicated, because now we have to worry about that pesky sign bit. As long as we’re still talking about positive binary numbers, we can still left pad with 0’s, even under two’s complement. It’s just with negative numbers we can’t.

      • J3ANP3T3R

        yep no matter how many zeroes is padded before 633 it will still be 633. however im concerned with binary values such as 0101 and 1010. i seem to not have a problem padding zeroes to the left of 0101 but i thought if i pad zeroes to the left of 1010 then that would make it from positive to negative. im really really slow with binaries pls excuse me in advance.

        • Alex

          It depends on the interpretation of the binary number. If the left-most bit is not a sign bit, then we can pad with zeros to the left no matter what the left-most bit is. If the left-most bit is a sign bit, then we would pad with whatever value the sign-bit is.

          Thus, 1010 would be padded as 0000 1010 if 1010 is an unsigned binary number (decimal 10), but would be padded as 1111 1010 if 1010 is a twos’s complement binary number (-118).

          • J3ANP3T3R

            Ohh got it ! thanks .. so i need to check first if the binary value is signed or unsigned.
            i was following the explanation below ;

            "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"

            it made me thought that given a binary value like 1010 i would check to see if the left most bit is 0 then its positive and if its 1 its negative so 1010 is negative but seeing the padded 0s i got confused as to how am i going to check if the left most value is 1 or 0 if i pad it with 0 it will always be positive etc. thanks i’m gonna read this section again until i can finally understand it arrggg…

            • Alex

              You’ve almost got it! Note that you can’t tell whether a number is signed or unsigned simply by looking at the bits. This is why the typing information is important -- it tells you how to interpret the bits.

  • Alex Paulo

    Hello Alex, my name is Alex too 🙂
    I love your turorial and i just want to say really really thanks for it!
    Im still working to fix somethings, but i just finished my Binary Calculator beta 1.0  
    (hehehe)

    It’s good?
    I’ve worked for some hours trying to use everything i learn from this tutorial 🙂

    PS: The result prints in vertical (im working to fix this).

    • Paul

      Hey, I know this is a few days old and you might have already worked it out, but on line 38 get rid of "\n"

      It should look like below instead

  • Jack

    Hello Alex, I’m using Xcode and I saw that the minimum size of my integers is 4 bytes. And I got confused. In the program in question 6, when we convert the input number into a binary, the program gives us 8 digits (#### ####). So I suppose it is 8 bits = 1 byte. But my integers are 4 bytes, so I tried to use instead of ‘int’ this: uint8_t. The fixed size int of 1 byte and the program didn’t work… What am I missing in my way of thinking? Shouldn’t I adjust the number of digits the program outputs to my size of int (4 bytes = 32 bits = #### ##…)? I hope you understand what my problem is 🙁

    • Alex

      Yes, even though we’re using an integer to hold x, really we’re just using 1 byte of x. You should definitely be able to use uint8_t instead -- what error did you get?

      • Jack

        So basically when we’re using an integer to hold x, we’re just using 1 byte of x and the three remaining are lost/dropped/unused? It’s not that I got an error, it was that no matter what number I put (0-255) the output showed: 0011 0001. Every single time when using uint8_t. Generally it’s better to use fixed-width integers?

        • Alex

          We’re constraining x to be a number between 0 and 255, so only 1 byte of x is used. The other 3 bytes are just unused.

          If you got the same output every time with uint8_t, then there was something else going on. 0011 0001 is binary for 49, which is number 1 in Ascii. I think what’s happening is you’re typing the number 1, but because uint8_t is often typedef’d as a char, it probably got interpreted as char ‘1’ instead of integer 1.

          The C++ committee really screwed up when they didn’t ensure that int8_t and uint8_t had to be discrete integer types with no char interpretations…

          • Jack

            You know what? It must have overlooked it because the code works fine actually… The binary number in the output is changing accordingly to what I type. I thought it’s always the same  but the end of the binary is really changing. However my question now is: why when I’m using uint8_t it’s using ASCII and if normal int it is not? When typing ‘4’ for example in int it is 0000 0100 and in uint8_t it is 0011 0100? It’s because it’s typedef’d as a char and chars are interpreted using ASCII?

            • Alex

              Some compilers typedef uint8_t as an unsigned char. On those browsers, std::cout will print uint8_t as a char instead of an integer. Unfortunately the C++ specification does not forbid this.

              • Jack

                Oh, I think I get it. So using my compiler (Xcode) I cannot use fixed-width integers instead of regular integers because the binary representation would be different? Or it doesn’t matter and I’m free to use it? Sorry for asking so many questions.

                • Alex

                  You can definitely use the fixed-width integers on xcode. You just need to be careful because int8_t and uint8_t may print as chars or integers depending on your compiler.

                • Jack

                  Okey, thank you for your reply and help. So if a compiler decides it is a char, it will use the ASCII code and in this particular exercise it prints different results depending on whether I use int or int8_t/uint8_t, correct?

                • Alex

                  Yup. So if you’re using int8_t or uint8_t, and you want to make sure it prints as an integer instead of a char, convert it to an int using static_cast.

                • Jack

                  Okay, thank you.

  • Lucas

    This is my approach and it works…What do you think, is it ok?

    • Jack

      I’m not sure if you asked me or Alex but as far as I know: if your code works properly, then it is correct. What I mean is there are many ways of expressing a certain idea within a code 🙂 but that is my opinion and I am a beginner still.

      P. S. I am still waiting for a reply to my question

    • Alex

      Yeah, it’s great. The quizzes take a more manual approach since we haven’t covered loops yet. But if we had, I’d definitely use a loop here.

  • functionLover

    functional programming to the rescue:

  • MOHIT PANDEY

    This doesn’t work properly.
    it is showing answer as 11111111.
    Plz help me.

    • Alex

      Your function bit() is returning a value, but the caller (function main) isn’t doing anything with it, so it’s being discarded. That means x never changes.

      You probably meant:

  • Gabi

    Is this ok?

  • Olvin Lizama

    Hi Alex,

    This is my Approach to the quiz, I tried to make my code that if in the future let’s say I need to convert a decimal to a binary of 16bit I can change it easily in few steps, I know we haven’t cover loops yet, but looking some examples before I got the general idea, here is my code.

    Thanks again for this awesome tutorial.

    Regards,

  • william

    When doing the number 6 quiz i got a very similar solution to yours. But only after i over complicated it and failed on the first try and started over.
    I was trying to make the solution more simple when i over complicated it.
    does anyone have any tips to prevent this?

    • Alex

      Not really. Sometimes you have to fail a few times before you find the right way forward.

      Someone once told me, “In programming, you have to write something once to know how you should have done it the first time”. There’s a lot of truth to that.

  • Kılıçarslan

  • matt

    Create a function called binary_converter. Inside the function, implement an algorithm to convert decimal numbers between 0 and 255 to their binary equivalents.

    For any invalid input, return string Invalid input.

    Anyone gat a clue on this?

  • Stephen

    Used a bunch of terrible coding practices, its messy but gets the job done. I need to use better practices with functions and stray awawy from procedural coding

    int convert_to_binary(int user_number);

    #include <iostream>
    #include "constants.h"
    using namespace std;
    int main()
    {
        int pow;
        int user_number;
        cout << "Please input a number between 0-255 to convert to binary \n";
        cin >> user_number;
        

        convert_to_binary(user_number);

        system("pause");
        return 0;
    }

    int convert_to_binary(int user_number)
    {
    #include "constants.h"

        if (user_number - eigth_digit >= 0)
        {
            cout << "1";
            user_number -= eigth_digit;
        }
        else {
            cout << "0";
        }

        if (user_number - seventh_digit >= 0)
        {
            cout << "1";
            user_number -= seventh_digit;
        }
        else {
            cout << "0";
        }

        if (user_number - sixth_digit >= 0)
        {
            cout << "1";
            user_number -= sixth_digit;
        }
        else {
            cout << "0";
        }

        if (user_number - fifth_digit >= 0)
        {
            cout << "1 ";
            user_number -= fifth_digit;
        }
        else {
            cout << "0 ";
                }

        if (user_number - fourth_digit >= 0)
        {
            cout << "1";
            user_number -= fourth_digit;
        }
        else {
            cout << "0";
                }

        if (user_number - third_digit >= 0)
        {
            cout << "1";
            user_number -= third_digit;
        }
        else {
            cout << "0";
                }

        if (user_number - second_digit >= 0)
        {
            cout << "1";
            user_number -= second_digit;
        }
        else {
            cout << "0";
                }
                
        if (user_number - first_digit >= 0)
        {
            cout << "1";
            user_number -= first_digit;
        }
        else {
            cout << "0";
                }

        return 0;
    }

  • George

    Hey Alex. Could you explain why you can’t put a return statement in an if statement with other things, for example question six you made two separate if statements executing the same parameters. I tried to put the return in with the output originally and it wouldn’t let me. Clearly it would be more efficient if they were together, soo… any reason?

  • Alex,

    Thank you so much for making it easy to learn C++. I am a hardware designer, and am learning C++ through your site. You are my teacher.

    Would you consider reviewing the solution to problem 6 whenever your schedule permits? Thanks!

    Kind regards,

    wtariq

    • Alex

      Overall, not bad. But a few thoughts on how to improve:
      1) Get rid of the global using namespace std.
      2) Using a u prefix on your variables doesn’t really accomplish much, and makes them harder to read.
      3) Comments would really help determine what your variables are intended to do
      4) You can refactor decimal_to_binary() to make it much simpler. Get rid of uBinNumber altogether and move just cout 0 or 1 inside your if statement. Then print an extra space subsequently if uSpace == 3.
      5) decimal_to_binary isn’t a good name for the function. printDecimalAsBinary would be better.

  • Brad

    I made the program with 8 functions, one for each bit. Then I saw how elegant your solution was. I keep forgetting about passing multiple arguments to one function.