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 digits (0 and 1), the value of each digit increases by a factor of 2. Just like commas are often used to make a large decimal number easy to read (e.g. 1,427,435), we often write binary numbers in groups of 4 bits to make them easier to read (e.g. 1101 0101).

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.

**What about converting floating point numbers from/to binary?**

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

**Quiz**

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 |

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.

I don't just understand this no matter how I try... Admin please is there a way I can get tutored.

Yes, you can hire a tutor from somewhere that offers this service. 🙂 Unfortunately, that's not here. 🙁

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.