In order to understand the bit manipulation operators, it is first necessary to understand how integers are represented in binary. 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 (eg. 1,427,435), we often write binary numbers in groups of 4 bits to make them easier to read.
Converting binary to decimal
In the following examples, we assume that we’re dealing with unsigned numbers.
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 multiple each binary digit by it’s bit value (determined by it’s position). Summing up all these values gives us the total.
| Binary digit | 0 | 1 | 0 | 1 | 1 | 1 | 1 | 0 |
| * Bit 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 |
| * Bit 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.
Converting decimal to binary
Converting from decimal to binary is a little more tricky, but still pretty straightforward. The easiest way to do this is to work backwards to figure out what each of the bits must be.
Consider the decimal number 148.
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 |
| * Bit value | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
| = Total (148) | 128 | 0 | 0 | 16 | 0 | 4 | 0 | 0 |
Let’s convert 117 to binary:
Is 117 >= 128? No, so the 128 bit must be 0.
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 = 0111 0101 binary.
Signed numbers
The following section is optional. Most of the time when we deal with binary numbers and bit operations, we use unsigned numbers. However, it is interesting to examine how signed numbers are dealt with.
Signed numbers 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 bit means the number is positive, and a 1 bit means the number is negative. Positive signed numbers are stored just like positive unsigned numbers. Negative signed numbers are stored as the inverse of the positive number, plus 1.
For example, here’s how we convert -5 to binary:
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 deal with negative numbers.
Quiz
1) Convert 0100 1101 to decimal.
2) Convert 93 to an 8-bit binary number.
Quiz answers
3.8 — Bitwise operators
|
Index
|
3.6 — Logical operators
|
3.8 — Bitwise operators
Index
3.6 — Logical operators
I have problem in binary Numbers & Logic Operations. can you help me to soulation of binary and decmal.
Thanks
Faiz
[ Try the lesson on bitwise operators. -Alex ]
Why do you say converting -11 to binary but then use a 76?
[ It should have been converting -76 to binary. Fixed! -Alex ]
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.
Thanks…….I thought u r gonna put me in a jail for spamming!! lol
[...] 2007 Prev/Next Posts « 3.7 — Converting between binary and decimal | Home | 4.1 — Blocks (compound statements) and local variables » Sunday, June [...]
[...] 2007 Prev/Next Posts « 3.5 — Relational operators (comparisons) | Home | 3.7 — Converting between binary and decimal » Friday, June 15th, 2007 at 1:35 [...]
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;
}
I should prob use an unsigned int though huh?
I’d say it’s not particularly relevant in this case since the range of x falls within both the signed and unsigned int range.
This is very cool! This piece of code works like a charm! Thank you! I will se this for my gaming and simlation classes!
two int main()s, I think you only need the second int main(). You are creating a function before before the int main() where your program begins.
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.
I found a website where you could buy doormats with the word “Welcome” printed on them in binary.
I’m guessing it just took the ASCII code for each letter in “Welcome” and converted those numbers to binary, which turns out to be “01110111011001010110110001100011011011110110110101100101″
which was four rows of numbers on the doormat :P
The caption said “Welcome your friends & family into your hi-tech culture!
Lol.
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.
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:
#include <iostream> using namespace std; int main() { cout << "Write a number to convert to binary: " << endl; long int nNumber; //user's number cin >> nNumber; cout << nNumber << " is" << endl; int nPower(16) ; //the power of 2 set capped at 16 while (nPower > 0) { if (nNumber >= (2^nPower)) //checkes if the number is greater than that bit. { cout << 1 << " "; // types 1 nNumber -= (2^nPower); //deletes that bit from the number } else { cout << 0 << " "; // types 0 } nPower -= 1; //dletes one from the power of 2 to check with. } return 0; }what’s up with it?
i didn’t understood the use of npower ….it is declared only not defined..
thanks koi
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
#include
main()
{int bit=128,num;/* bitwise binary conversion*/
scanf(“%d”,&num);
while(bit>=1)
{if(num>=bit)
{printf(“1″);
num=num-bit;}
else
printf(“0″);
bit=bit/2;}
}
Wait, so the smallest negative binary number (signed) is 127, or am I missing something?
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)
I got it. http://www.edsim51.com/sampleChapter.pdf (Page 1 and 2.)
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)