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.

**Converting integers to binary two’s complement**

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.

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

If adding in binary is difficult for you, you can convert to decimal first, and then add 1.

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

3.8 -- Bitwise operators |

Index |

3.6 -- Logical operators |

Quiz 6). Comments to your answer. I thought "using namespace std;" is very convenient, but you did not use it. Why? Why two identical "if" statements are not combined? As always, fascinated by your efforts.

using namespace std; is generally bad practice because it significant increases the risk of naming collisions. I discuss this more in chapter 4.

I used two almost-identical if-statements only because I haven’t covered compound statements (blocks) yet. I cover those in… chapter 5 I think.

Using some prior knowledge of loops and arrays (as well as that nice ?: operator a few sections back), I tried to get as "clean" an answer for question six as I could. I’m not sure how actually efficient this solution is, but it worked nonetheless:

(Didn’t add a check for an invalid input however, but hey.)

I am sorry but i do not quite get it

int main()

{

signed int a = 180;

std::cout<<(int)a;

return 0;

}

This is my program, and the output i get in g++ is 180 regardless of wheter i use int or signed int. Can you please help me out here?

You used an int here, which is probably 4 bytes on your system. You need to use a data type that’s only 1 byte. that’s why I suggested char.

This prints -76.

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.

My doubt is: isnt ‘int’ by default ‘signed int’? so if the number i had entered was x = 180; , wont the compiler assume that it is -76, considering its type is signed int?

Thankyou

Yes, integers in C++ default to signed. So an 8-bit signed integer (range -128 to 127) that assigned values 180 would print as -76. You can try this yourself with a signed char (static_cast it to an int before printing so it prints as an int instead of a char).

When thinking about the question I could only think of storing the info in an array. I was thinking that that it would be easy to scale as well (if you wanted to do larger numbers). If you have any advice I would appreciate it.

While doing my homework assignment I wanted to complicate things, in the spirit of learning. So… I decided I wanted my program to let the user input anything and output the binary representation of that input (if the user entered an integer) or display an error message (if the user enters garbage or an integer that is out of range). I got carried away in my homework and the result is 200 lines of code (well… including comments).

I have a feeling that my program is not as efficient as it could be. Any ideas about how to make it more concise and efficient are welcome. I would also want to know if my comments or identifiers could be improved.

https://pastebin.com/a6Ayg4xf

You certainly did go beyond. I don’t have any immediate suggestions for you. 🙂

ctrl + F "the the compiler"

I assume you only intended to use "the" once.

So you said in two’s complement, the most significant bit 0 = positive and 1 = negative.

What about large numbers like -211?

211 = 1101 0011

The inverse +1 = 0010 1101

Even though it’s meant to be -211, the binary still starts with a 0…or are you unable to use two’s complement after a certain point?

-211 requires 9 bits to store. This is because unsigned and signed numbers have different ranges.

With an unsigned number, the range is 0 to 255, so as you’ve noted, 211 = 1101 0011. However, with a signed number, half of the range goes to negative numbers, so the range is only -128 to 127. This means -211 is out of range of an 8-bit signed number, and requires an extra bit.

The proper conversion would be 211 = 0 1101 0011 inverted + 1 -> 1 0010 1101

Okay! That makes sense. I was thinking that might be the case but wasn’t completely sure…and now that I think about it, it was kinda covered in an earlier chapter. I appreciate the feedback.

What can i do to put the outputs into the right order.

Btw i used the 1st method because i tried the 2nd method yesterday and failed miserably so i looked at the solution. I didn’t wanted to cheat myself so i tried to do it with the 1st method today. Help would be appreciated. Thanks

Reversing the bit numbers is non-trivial given the concepts we’ve covered so far. Probably the easiest way is to put them into a std::string and then print the string when you’re done.

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

I think it would be easier to also teach people to just solve the reverse version of the unsigned binary and just add 1 to the answer?

For me it was much easier to understand, I just did the table for 0101 1101 = -93 then just add 1 = -94.

I noted this in the lesson. Thanks for the contribution!

i wrote my own program and its working perfect.

if you have any suggestion please tell me.

While I did first implement working code using only theory provided previously, I also figured out how to do quiz question 6 using a while statement:

Unfortunately I couldn’t figure out a better workaround for using the pow(base, exponent) function than having separate input parameters for the exponent as double and int types, using each type where appropriate (exponent for the pow() function and int for the modulus operator), and decrementing each variable at the end of the loop.

So this may not be the right place to ask since this is more of a background of C/C++ question rather than a question about programming in C/C++, but why all the bit flipping for negative numbers? Wouldn’t it be easier to just look at the leftmost bit to determine positive or negative and call it a day? i.e. 1011 and 0011. The last three digits of both being the same. Wouldn’t it be easier to just say both are 3, the only difference being the first starts with a 1 making it -3?

Negative numbers are stored as the inverse of the positive numbers so that when you add a positive and a negative number, you get 0. It makes doing math with such numbers much easier.

Just wondering, why would we need to know this in the future?

Pieces of this are used in the next lessons, when dealing with bitwise operators and bit flags.

Could you explain why we return x - pow ?

In the second method, when a bit is determined to be a “1”, you subtract out the value of that bit (pow) so you know how many more bits of value you need to find.

In the lesson, it’s the doing the equivalent of this line:

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

That “148 - 128” part is “x - pow”, leaving you with 20 remaining that you need to find bits for.

Thank you for comprehensive answer!

First I built a version of this that printed everything in reverse order. I haven’t gotten to the part of these lessons that help me clear that up yet, so then I tried a variation of the given solution. It works fine, as far as I can tell, but any suggestions or warnings on faulty thinking would be helpful!

The only major issue I see is that integerInput() calls itself, which you shouldn’t do. Use a loop instead of a recursive function call. As a minor issue, you’re better off commenting your variables where they are defined rather than at the top of the function.

I’ll keep both of that in mind! Thank you!

Here’s my solution, using recursion, method 1. It accepts a positive integer and prints its binary representation, formatted to groups of 4 and padded with 0s up to the nearest group of 4:

Please tell me if i used something that is a bad practice and what i should do instead.

1) Function parameter y needs a better name (e.g. maxLevel).

2) Your for loop can have an empty initialization portion (x does nothing there)

3) You can define variable bit and initialize it on the same line rather than doing an assignment on the subsequent line

4) Your if statement doesn’t need the curly braces since the statement portion is just one statement.

5) bitx needs a better name (e.g. printBits)

Thanks for answer, i have further question about 2)

I’ve tried to write instead of

this:

but it does not compile.

I know i can use while cycle here, but i want to understand how to do for in this case.

I see now, it has to look like for(; y>0; y=y/2)

sorry

You need a semicolon before the y>0;. That way C++ will know that the for loop has an empty initialization section.

Is my uses of commas acceptable?

Using the comma operator in this way is non-conventional (comma normally isn’t used outside of for loops). But the meaning of each statement is straightforward enough that I don’t have any particular concerns about it.

I understand that it’s dangerous that I’m using somewhat loop statements when we haven’t covered that lesson yet. I tried my hand at method 1 (I try to do the quizzes without reading the hints), and my only problem was printing "001111" backwards into "111100" which correctly displays the input, 60. Is there anyway to do this using the information given so far, and if there isn’t, can you still tell me what would solve this? Thank you so much, as always.

oops I tried editing after already submitting, and it messed up the code thing!

There are several ways to deal with “flipping” the results of method 1. First would be to store the results in a string or array and once you have them all, write them out in reverse order. The second method would be to use recursion and write out the results after the recursive function call so they write in reverse order. I haven’t talked about std::string, arrays, or recursion yet, so you’d have to read ahead if you want to pursue any of these.

Method 2 is a lot simpler since you don’t need to store the results temporarily.

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.

I mean, it works. But, it’s so redundant.

Most times you have a bunch of statements or functions that are almost identical, you can probably collapse them into something simpler by parameterizing something. A lot of times writing things out “the long way” (like you’ve done above) helps you see where the differences are.

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

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.

Thank you for your valuable inputs.

Best.

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?

You can, we just haven’t covered how yet:

if (x >= pow)

{

std::cout << "1"; return x - pow; } else { std::cout << "0"; return x; } [/code]

Ok, thanks, nice to know 🙂

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;

}

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?

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?

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.

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,

Is this ok?

Mostly. It would be better if insertNumber() didn’t need to call itself. This code could also benefit from some comments/documentation. 🙂

This doesn’t work properly.

it is showing answer as 11111111.

Plz help me.

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:

functional programming to the rescue:

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

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

It was for Alex, but thanks anyway for your toughts. I m a beginner in programming too.

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.

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 🙁

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?

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?

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…

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?

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.

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.

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.

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?

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.

Okay, thank you.

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

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

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

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.

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.

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

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…

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.

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 ?

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.

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

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!

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!

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:

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

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

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

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!

Thanks! I’ve fixed this.

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

Awesome, that is easier. I’ve updated the lesson accordingly. Much appreciated.

You’re welcome. For consistency could you please also update Solution 5) in the ‘Quiz answers’ section? Thanks.

Done! Thanks for the reminder. 🙂

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?

I don’t know. I suspect a typo somewhere, because the solution supplied works fine.

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?

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?

Thanks for this clarification. Like others, I was still confused about the left bit concept until I saw this lol

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.

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

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

By the way please remove the comments during compilation

,THANX

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.

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

Mine is a bit different.

How I can improve my code?

Thanks!!

The last dec /= 2 is unnecessary, and r6 is printed twice. But other than that, it’s fine for what it is.

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

Hint: You never do anything with the return value from convert().

Also, your convert() function is indented strangely (perhaps mistakenly). The return statement isn’t part of the else statement (if you want it to be, you need to put it inside a block).

Thanks Alex 🙂

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.

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

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

my answer of question 6 for n bit representation

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.

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

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;

}

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.

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!

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.

But what happens when the file already is executable?

Btw - Thank you very much, Im very glad i found this tutorial!

Thanks for everything!

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.

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

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

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.

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

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!

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

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

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?

plz help

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

try this:

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:

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

how do I fix it?

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

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

x - pow is an integer minus a double, which resolves to a double. But your function returns an int, so the double gets implicit converted to an int (which can result in a loss of data, hence the warning).

This one is easy to fix: Since pow is always an integer, make it an integer parameter.

how would one go about doing that?

Change:

to

(x needs to be changed too)

I tried what you said but it still dosn’t want to work. same problem:(

Oh, variable x in main should also be type int.