While you may not ever use binary operations for simple programming tasks, it doesn't hurt to know about them in case you see them in someone else's code. Before we get to binary operations, though, I'll say a few words about binary numbers.
Binary Numbers
Binary numbers are in base 2, unlike the base 10 number system we normally use for counting. Thus, instead of having digits from 0 to 9, a binary system has only 0 and 1. And further, instead of a ones place, a tens place, and so on, binary numbers have a ones place, a twos place, a fours place, and every other power of two. so lets take the number fifteen, for example. In our base 10 system, that would be written as 15. But in a binary system, fifteen is represented as 1111; one eight, one four, one two, and one one. Likewise, sixteen is 10000. A single byte, which you'll remember is eight bits long (each place in a binary number corresponds to a bit), there are 256 numbers, since the eigth bit is the 128 place.
As an aside, C also supports the other funny counting systems used in computer science, hexadecimal and octal, which are base sixteen and eight, respectively. Hex numbers use the digits 0 through 9 and additionally A through F, to represent 10 through 15. In C, hex numbers begin with
0x
. Octal numbers use only the digits from 0 to 7, and are represented with a leading0
.
Operations
So what kinds of things can you do with binary numbers? Well, for starters, you can shift their bits around. The left shift operator is
<<
, and the right shift operator is>>
. Each has the form thing to be shiftedoperator
# places to shift. Take a look at the following snippet of code:
char ch = 'N'; /* ASCII code 78, or 01001110 in binary */ ch >>= 1; /* Now ch is 00100111, or 39 */ printf("%c\n", ch); /* Prints ', the single quote mark */The code prints out the single quote mark since that is ASCII code 39. Note that you can use the shortened form
>>=
just as you can with other operators.The logical operations also have a parallel in binary applications. Instead of using double symbols (i.e.
&&
and||
), though, you use the single versions.&
is binary and, which returns true if the bits on either side are each on (1).|
is binary or, which returns true if either of the bits are on. There is also^
, exclusive or, or XOR, that returns true if one but not the other bit is on.
Back to More About I/O | On to Section 3: Abstract Data Structures and Algorithms | |
Back to the Outline |