Showing posts with label Binary. Show all posts
Showing posts with label Binary. Show all posts

Saturday, May 21, 2011

PHP Lesson 2: Expressions & Operators

Like many programming languages, PHP deals with expressions (as in, mathematical expressions.) In fact, almost every PHP statement, other than certain "language constructs" (which you will learn about later) is also a mathematical expression.

An expression consists of operators, operands, and sometimes parenthesis (to override the order of operations.) An operator is something like one of these:

+ - * / (meaning plus, minus, times, and divide)

An operand is something that an operator works with. So in the following expression...

3 + 4

... the operator is + and the operands are 3 and 4.

As it turns out, there are a lot more things considered to be operators than just those four basic arithmetic operations. One of the most important operators is "the assignment operator", which is represented by a single equal sign. The assignment operator requires a variable to be specified on the left hand side. The right hand side is evaluated and whatever the answer is is stored into the variable on the left side. In PHP, all variables begin with a dollar sign, and have names which must start with a letter or underscore, and consist of letters, numbers, and underscores.

$myVariable = 3 + 4;

The order of operations deems that assignments happen last. So first, 3 and 4 are added together to get 7, then the 7 is stored into $myVariable. Easy, huh?

PHP lets you make up a new variable on the spot by doing exactly that. Just pick a name you haven't used before, and assign something to it! It's that easy.

Once you've assigned a value to a variable, you may use the variable within other expressions, and you may also choose to reassign it to a different value later. (This is done in exactly the same way as you first assigned it.)

$x = 4;
$y = 10;
$z = $x * $y;
$x = 1;

You should be able to identify the variables, the operators and operands, and tell apart the operands which are numeric literals from those which are references to variables. You should also be able to determine what the value of each of the named variables will be when those four lines of code are finished executing.

So, numbers aren't the only thing PHP can work with. PHP also works with strings of text, as you learned in the Hello World lesson. As it turns out, strings may be used as operands for some of PHP's operators, as well as numbers, and there is even a special operator that is designed exclusively for strings. It is called the concatenation operator and the symbol for it is the period.

$a = "Box";
$b = "Purple";
$c = $b . $a;

To concatenate means to tack one thing onto the end of another. After running the above code, the variable $c will hold the value "PurpleBox" (without any space, because neither of the concatenated variables had a space anywhere in it.)

You can also concatenate literals, by specifying them in quotes, so we could fix the space issue by changing that last line to read:

$c = $b . " " . $a;

Thus we are concatenating the value of variable $b with a blank space (represented as a single space wrapped in quotes), and concatenating that with the value of variable $a. If you try to concatenate a number, PHP automatically converts the number into a string representation of the number in decimal.

Mathematical Operators: Each of these takes two numbers for input and gives a number for output.

-$b ... Opposite. Turns a positive value negative or a negative value positive.
$a + $b ... Addition.
$a - $b ... Subtraction.
$a * $b ... Multiplication.
$a / $b ... Division.
$a % $b ... Modulus (The remainder of integer division)
$a & $b ... Bitwise AND
$a | $b ... Bitwise OR
$a ^ $b ... Bitwise XOR
$a << $n ... Shift the binary value of $a left by $n bits.
$a >> $n ... Shift the binary value of $a right by $n bits.

Logical Operators: Each of these takes two Boolean values for inputs and gives back a Boolean value as an output. See below for rules on what values are considered true or false.

!$a ... Logical NOT
$a && $b ... Logical AND
$a || $b ... Logical OR
$a xor $b ... Logical XOR

Other Operators:

$a = $b ... Assignment.
$a . $b ... Concatenation of Strings.

Comparison Operators: Each of these gives back a Boolean value as an output.

$a == $b ... Is equal to
$a != $b ... Is not equal to
$a > $b ... Is greater than
$a >= $b ... Is greater than or equal to
$a < $b ... Is less than
$a <= $b ... Is less than or equal to
$a === $b ... Is exactly equal to (We will talk about what this means in another post.)
$a !== $b ... Is not exactly equal to (Again, in another post...)

When comparing strings, dictionary order is used to determine lessness or greatness. "z" is greater than "a" and "1000" as a string is less than "12", but the number 1000 is greater than the number 12.

Do all Operators Return Something?

3 + 4 returns 7. But do all the operators return something?

What about $x = 6? Yes, in fact, in addition to storing 6 into $x, it also returns the same value as its own result. Because of this, you can use an odd shortcut like this:

$z = ($x = 6);

This will take the 6, store it in $x, then store the "answer" of $x = 6 into $z. In actuality, the parenthesis here are not needed. I only put them in for clarity to show the sequence of steps.

Is it True or False?

This little section about True and False values might not make a lot of sense yet, but I'm putting it here anyway...

PHP has a way of considering values as true or false even if they are of a type other than boolean. Here are the rules:

A boolean is considered true if it is true, and false if it is false. (I didn't even need to write that!)
A number is considered false if it is zero, but any other number is considered true.
A blank string is considered false, as well as a string containing only the zero character (this way a number after having been converted to a string retains the same true/false value as the original number.) Any other string is considered true.

Order of Operations

So, with so many operators it would be good to have an idea of what the order of operations are so we know when to use parenthesis and when not to. Here it is, in a nutshell, considering all the operators we have learned so far. You don't need to memorize this, just get the general idea of it. Mainly, that its a lot like regular math and that assignment comes last:

First comes ! (not), then multiplication division and modulus (* / %), then addition, subtraction, and concatenation (+ - .), then the bit shifting operators, then comparison operators involving greater than or less than, then comparison operators involving only equality or inequality, then bitwise operators, then logical operators, and finally the assignment operator.

Putting it Together

Please note that I'm not going to be writing the magic PHP tag at the top of each code example (mainly because it is too hard to input angle brackets on blogger,) but it does indeed need to be present at the top of each of your programs...

$name = "Jeff";
$x = 29;
echo $name . " is currently " . $x . " years old.\r\n";
echo "He will be turning " . ($x + 1) . " years old on his birthday.\r\n";

Notice that because addition and concatenation are at the same level of precedence (in the order of operations), I was required to put the $x + 1 in parenthesis so the addition problem would be calculated first and then the answer concatenated onto the string. If I were to forget the parenthesis, $x would get concatenated first, and then an attempt would be made to add the number one to the entire string "He will be turning 29" ... Doing so would end up forcing the string to be converted into a number (since it begins with text and not numeric digits, it ends up getting converted to the number zero), after which the number 1 is added, leaving us with only the answer 1, and finally the concluding string " years old on his birthday.\r\n" would be concatenated onto this 1 (which would first automatically be converted back into a string. So when parenthesis are left out, the result of the entire thing works out to "1 years old on his birthday.\r\n"; and when they are left in the result is "He will be turning 30 years old on his birthday.\r\n";

Next Post: Controlling the Flow of the Program

Wednesday, May 18, 2011

Binary Logic

Binary Logic is the subject covering logical operations which may be performed on binary (0 or 1) values. Sometimes it is called Boolean Logic because the field was pioneered by George Boole in the 1800's.

The Significance of 1 and 0 aside from being Numbers...

I would like to expand your understanding of what a binary digit represents. It is more than just a tiny number. We talked last lesson about how 1 represents the presence of electrical current and 0 represents its absence. In regular language these possibilities could be considered "on" and "off." A single bit (hint: bit is short for binary digit) taken by itself can actually be quite meaningful, when its values are considered in the following way:

0 = off = false = no
1 = on = true = yes

Think about how often we use yes or no to answer questions in our day to day life. In school you probably took many quizzes or tests featuring problems with True or False answers.

Binary Logic Operations

The simplest logical operation we can apply to a binary value is NOT.

Operation: NOT

NOT simply "flips" or "inverts" the bit:

NOT 1 = 0
NOT 0 = 1

Even though NOT operates upon a binary value, it is called a Unary operator because it only takes one input to achieve its output. The other operations in this lesson are binary operators because they take two inputs.

Operation: OR

So, now lets take a look at OR. In the world of binary logic, the outcome of X OR Y is true if either X or Y is true, or if both are true. In fact, the only way X OR Y can be false is if both of the inputs are false.

When we make a list of all the possible inputs and outputs, this is called a "Truth Table." The Truth Table for OR is:

0 OR 0 = 0
0 OR 1 = 1
1 OR 0 = 1
1 OR 1 = 1

Another way to look at it is like this:

X Y (X OR Y)
000
011
101
111

Operation: AND

The outcome of X and Y is true only if both inputs X and Y are true.

0 AND 0 = 0
0 AND 1 = 0
1 AND 0 = 0
1 AND 1 = 1

Operation: XOR

XOR means "Exclusive OR" The outcome of X xor Y is true if either of the inputs X or Y are true but NOT both of them.

0 XOR 0 = 0
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0

You can apply a NOT to the result of the three binary operators we have learned so far to come up with three additional operations...

Operation: NOR

0 NOR 0 = 1
0 NOR 1 = 0
1 NOR 0 = 0
1 NOR 1 = 0

Operation: NAND

0 NAND 0 = 1
0 NAND 1 = 1
1 NAND 0 = 1
1 NAND 1 = 0

Operation: NXOR (also called XNOR)

0 NXOR 0 = 1
0 NXOR 1 = 0
1 NXOR 0 = 0
1 NXOR 1 = 1

Logical vs. Bitwise

In some programming languages you will discover that there are different operators for "logical" OR as opposed to "bitwise" OR (and likewise for all of the other operators.) I want to clear up the mystery behind this right now. Logical OR is what we've been talking about above. It takes the item on the left and right side of the OR and treats each as a true or false value, and gives you a true or false result. Bitwise OR is just a shortcut for doing a bunch of these at once. It takes the left side and the right side as two binary numbers, and performs a logical operation on each of the digits in sequence, for example:

Bitwise AND:

100101
&111011
========
100001

You will notice that each of the place values considered separately is simply a logical AND operation as explained previously.

Well, that's it...

The meaning of all the binary logic operators has been explained above. All other mathematical operations can be derived by applying these binary logic operations in different combinations.

Next Post: "Hello World" in PHP at the Command Line.

How to Count in Binary, Octal, and Hexadecimal

Programming has something to do with Math and Logic. I think it is valuable for a beginning programmer to have a reference to the type of math which makes computers work... So, here it is:

Counting Like a Programmer

Since computers are all composed of electrical signals and switching mechanisms which are either turned on or off, the computer works in "1's and 0's." Basically, the 1 means electricity is flowing in a particular bit of memory, and the 0 means it is absent.

Humans have ten fingers, so we developed a base-10 system where we have the digits 0 through 9 to represent our basic type of counting. When we run out of symbols (get to 9) we solve the problem by adding a new place, the "tens place" and then starting over with a zero in the one's place, in other words, after 9 we find the number "10" (ten) which occupies two digits.

In the computer, only the digits 0 and 1 really exist on the electrical level, so it counts from 0 to 1, then it runs out of symbols and has to add a new place. But in this case, it is the "twos place", and counting starts over with a zero in the one's place. So after the number 1 in binary comes 10. Binary is also called base-2. When we are counting in other bases besides decimal, we don't say things like "ten" and "seventeen", because those are exact decimal amounts, instead when we look at the binary number 10 we speak it out loud by saying "one zero" or even "two" (actually saying two is converting it back to decimal for the purpose of speaking its meaning aloud.)

In Decimal, the place values are one's place, ten's place, hundred's place, thousand's place, etc. And in binary they are the one's place, two's place, four's place, eight's place, sixteen's place, thirty-two's place, sixty-four's place, and one hundred twenty eight's place, etc. In other words, each digit has double the place value of the digit to its right. These are the "powers of two" and you will see this series of numbers often in computing. I've been programming for about 18 years and I can give this much of the sequence easily off the top of my head: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, etc. You don't need to try to memorize that sequence, but knowing the first few powers of two may be helpful.

Counting in Binary compared to Decimal, Hexadecimal, and Octal:
Binary Decimal Hexadecimal Octal
0000 0 0 0
0001 1 1 1
0010 2 2 2
0011 3 3 3
0100 4 4 4
0101 5 5 5
0110 6 6 6
0111 7 7 7
1000 8 8 10
1001 9 9 11
1010 10 A 12
1011 11 B 13
1100 12 C 14
1101 13 D 15
1110 14 E 16
1111 15 F 17
10000 16 10 20

(In the above table, I prefixed the binary numbers with zero to pad them out to four digits in length merely as custom. As with decimal numbers, leading zeros are unimportant to meaning.)

Binary takes a lot of writing if you wish to record large numbers, so computer programmers have used certain types of shorthand to make the representation of binary easier to deal with. Converting to decimal would be one way to handle it, but it is not very easy to convert between binary and decimal in your head, so instead programmers have made use of the Hexadecimal (base-16) and Octal (base-8) systems, which I will now explain:

You will observe in the chart above that every four digit binary number corresponds exactly to one hexadecimal digit. Hexadecimal is a system using the digits 0 through 9 and A through F, a total of sixteen possible values (zero through fifteen) instead of only using 0 through 9 like the decimal system does. In Hexadecimal, when you have counted all the way up to F, you have to put a 1 into the sixteen's place, and then start over with zero in the one's place, giving you the hexadecimal number "10" (one zero, or sixteen.) Because of this, you can convert a long binary number into Hexadecimal just by breaking it into groups of four starting on the right (least significant) side of the number, and then switching to the appropriate hex digit. Example:

I want to convert this number: 101101010100010110101110100101

So first I break it into groups of four, starting on the right. You'll notice there are a couple of extra digits left over on the left side:

10 1101 0101 0001 0110 1011 1010 0101

Now I convert each group of four into its corresponding hex digit. Starting from the right, 0101 becomes 5, then 1010 becomes A, 1011 becomes B, 0110 becomes 6, 0001 becomes 1, 0101 becomes 5, 1101 becomes D, and we pad the leftover digits with zeros on the left, so 10 is considered as 0010 and it becomes 2:

00101101010100010110101110100101
2D516BA5

So the resulting hex number is: 2D516BA5.

Like that.. Easy, huh?

Convert back is done the same way. Just take each hex digit, and translate it back into the four corresponding binary digits.

Converting to and from octal works the same way except that each octal digit corresponds with a group of three binary digits instead of four. People don't use octal very much today in programming, but it is used in the numeric file permissions on Linux and Unix based computers, so you will see it from time to time.

Something odd about me...

So, I have developed a habit of counting in binary using my fingers in the following way. I have assigned each finger a place value, and to represent a certain number I press those fingers against the table top. I leave the other fingers lifted. I have practiced counting this way with my fingers and I can count from zero to fifteen in binary in less than two seconds.

If most people were going to try to do this, they would probably assign the place values to the fingers in order, but since I was a trumpet player, I let the middle, index, and ring fingers be assigned the first three places, that way the first part of the sequence is the same as a descending chromatic scale on a trumpet. So, I assign my fingers values like this: middle finger = one's place, index finger = two's place, ring finger = four's place, pinky = eight's place, thumb = sixteen's place. But, that's just me and my weird habit. You don't need to learn to drum out binary on the table top if you don't want to!

Converting from Binary to Decimal and Back

So, there is one last thing. The nasty part of this lesson. How to convert between Binary and Decimal. To go from Binary to Decimal is pretty easy, just look at all the digits with a "1" in them, and add up the place values of those digits. For example:

10011

There is a 1 in the one's place, the two's place, and the sixteen's place, so we add those together: 16 + 2 + 1 and get 19. The decimal equivalent of this number is 19.

To convert the other direction is harder, but only because we have to subtract. Start with the decimal number, in this case, we will use 21. Start with a binary number of all zeros, then find the biggest place value that is smaller than this number, subtract the place value from the number, and mark a 1 in its place. In this case, 16 is the number, so we take 21 - 16 and get 5, putting a 1 in the sixteen's place. Now we repeat the process, the biggest number we can subtract is 4, so we take 5 - 4 and get 1, putting a 1 in the four's place. Now we have 1 left, 1 - 1 = 0 so we put a 1 in the 1's place.

The binary is therefore: 10101.

Try this a few times. If you need to, you can check your work by using the Calculator program on your computer when it is set to Programming mode. Make sure the base is set to the base you are converting from, then enter the number and flip to the base you want to see the same number represented in.

Wrapping it Up

I know this lesson was a little dry. I mean, who wants to do a bunch of Math, right? But it is an important subject which will help you a lot later on. The next few posts should be a lot more fun.

Next Post: Binary Logic.