Tuesday, June 7, 2011

PHP Lesson 4: I/O - Input and Output

As I mentioned in lesson 1, we are using PHP from the command line for interactive programming. This is different from the typical usage of PHP as a tool for helping to build websites. So far, we've managed to do output to the screen by using the echo command, but in order to make a truly interactive program we also need to handle input. Since PHP is normally running as a back-end tool on a web server, it isn't ready to receive input from the keyboard until you tell it that's what you're going to be doing. We do this by opening the "standard input" as if it were a file. Standard Input, or stdin is programming jargon for the "keyboard," in most cases. It takes one line of code to open the standard input and store it in a file handle called $stdin:
$stdin = fopen("php://stdin", "r");
A file handle is a variable, just like the other variables we used to store numbers and strings in previous lessons, except that it stores detailed information about a file which is opened for reading or writing or both. In this case, we opened the file for reading by passing a string containing the "r" flag. (A flag in this case is just a single letter code which has a special meaning to the fopen function.)

Wait... what is that fopen thing? It is a function. We will learn more about functions in a later lesson, but for now I will just say this. Remember the f(x) notation from math class in school? You probably used it in trigonometry to talk about sine and cosine, sin(x) and cos(y), and so forth. For now, it will suffice to think of a function as an operation with a name that takes input (given in parenthesis) and returns an item of output... in the case of fopen, the name of the function is fopen, the input is the filename and the mode, and the output is a file handle.

What does php://stdin mean, anyway?

Ok, so that doesn't exactly look like a filename, does it? In most places where PHP can accept a filename, it can also accept a URL. (Actually a URI, but that's another lecture!) PHP is very web-oriented and modern in this sense. If a filename has been specified which does not include a protocol specifier (the part before the ://) it is assumed to be a local file, and the local file system's protocol specifier is presumed (file://). The most common protocol specifiers aside from this are http:// and https:// which allow the reading from a webpage (either plainly transmitted or using the secure socket layer technology) as if it were a file. You may use these quite frequently in the future. But, in addition to these, PHP also has its own built-in "fake protocol" in order to allow access to input, output, and a few other things, and it uses the fake protocol specifier "php://" to accomplish this feat.

So to sum up, what it really means is this: We want to open stdin, but we know it isn't actually a file on disk, and it isn't a website either ... in our case, it's the keyboard ... so we have to put php:// in front of it so PHP knows that we're asking for its special stdin file handle which reads typed characters from the keyboard, and that we're not asking for some other thing on the system which happens to be named stdin.

Side Bar: The Relation between Operators and Functions

I want to point out that operators are really just a form of "syntactic sugar" and everything could actually be done in function notation if the language designers had chosen to do so.

For example:
x = a + b * c
The above expression could be re-written as shown below, had the language designers chosen to provide function notation in lieu of operators:
assign(x, add(a, mul(b, c)))
In reality, these particular functions (assign, add, and mul) are not built into PHP, because the designers of PHP have instead chosen to provide operators, but what I'm trying to get across here is the idea that operator notation and function notation serve the same purpose. They perform an operation and return a result.

The number of operators available is limited, because they are based on the symbols on the keyboard. In PHP these operators are usually one or two symbols in length (+, -, *, /, ^, =, &&, <=, etc.) Functions, on the other hand, are virtually unlimited in number, because they can have a lengthy name, following the same naming rules as an identifier for a variable (except that function names are not prefixed with a dollar sign as variable names are.) In fact, there are thousands of functions predefined in PHP, and you can also define your own custom functions—a topic we will explore in our next lesson.

Reading from Standard Input

So we've used fopen to open a "file" named "php://stdin" in read-only mode, and we've stored the handle to this file in a new variable called $stdin. What can we do with it now?

There is a function called fgets which reads a string from a file. It will read until a newline character (or an end-of-file marker) is reached. When used in conjunction with the keyboard via stdin, it will read until the user presses the Enter key, and the value read will include the newline character created by the Enter key itself.

Example of usage:
$s = fgets($stdin);
In this example, a line of text is read from the $stdin file, and is saved into the variable called $s.

Now, lets print out the value we read so we can see what it looked like:
echo "I believe " . $s . " is what you typed.";
So your program, excluding the magic PHP tag at the top, should now look something like this:

$stdin = fopen("php://stdin", "r");
echo "Please type something: ";
$s = fgets($stdin);
echo "I believe " . $s . " is what you typed.";

I've added an additional echo statement before the fgets to provide a prompt. If I didn't do this, the program would run and just sit there with a blinking cursor, so I figured it would be good to clue the user of the program in on what we're expecting.

Go ahead and run it and see what happens. I will enter "something" as my text. I'm going to show the entire console output I get beginning from the prompt where I ran the program:

jeffd@mercury:~/programming$ php something.php
Please type something: something
I believe something
is what you typed.jeffd@mercury:~/programming:$

So, it did exactly what we asked it to, but we have two basic problems with our program, both of which have to do with the location of newline codes. First, you will see that our output, which should have been "I believe something is what you typed." ended up having a newline in it. This is because fgets, when reading input from the user, includes the newline which marked the end of the input as part of the result. We can fix this by using the trim() function which removes all whitespace from the beginning and end of a string. This will remove any and all spaces, tab characters, and carriage return or newline characters from the beginning or the end of the string. Our modified line of code for receiving the input looks like this:
$s = trim(fgets($stdin));
The next problem is that when our program ended, the command prompt was printed onto the same line as the final line of our output. This doesn't look good, so to fix it, we should output a carriage return and new line sequence at the end of the program by adding this line of code at the end of the program:
echo "\r\n";
Our completed program code looks like this:
$stdin = fopen("php://stdin", "r");
echo "Please type something: ";
$s = trim(fgets($stdin));
echo "I believe " . $s . " is what you typed.";
echo "\r\n";
And the program output now looks like this:
jeffd@mercury:~/programming$ php something.php
Please type something: something
I believe something is what you typed.
jeffd@mercury:~/programming$
Ok, that looks great! So in this lesson we've successfully done Input and Output. I want to bring to your attention that with the knowledge you now have you may begin to use the if statement from the previous lesson to branch your program (cause it to do different things) depending on the text which was entered by the user. Remember, when comparing text, PHP is case sensitive. So, for example, if you ask a yes or no question, a response of "Y" is different than a response of "y", and both cases need to be taken into account if you wish your program to work as expected.

Some Tips About Prompts

I would suggest that whenever your program is awaiting input from the user, it should first output a clear question followed by either "? " or ": ", that is a question mark or a colon followed by a space. If you are asking a multiple choice question, you may list the valid answers in brackets (or in parenthesis, but stay consistent) before the colon, such as this:
Do you want to continue? [Y/n]: _
I have placed an underscore above to indicate where the cursor would be blinking while awaiting the user's input. If you have a default choice which will take effect of the user presses enter without answering, it should be shown in uppercase, as the Y is in the above prompt example, in the case of a fill-in-the-blank type of answer, indicate the default in brackets or parenthesis, like so:
In what directory do you wish to save your files? [/home/jeffd]: _
Well, that's it for this time!

Next Post: Functions

Sunday, May 29, 2011

PHP Lesson 3: Controlling the Flow of the Program

Quick Review:

In PHP Lesson 1, we learned how to install PHP, how to use nano to enter and save the source code of a program, and how to use php to run the program. We then used nano again to edit it to make corrections, and finally used php to run it again and show the updated output.

In PHP Lesson 2, we learned how to use expressions consisting of operators and operands to manipulate numeric, boolean, and string values and to store them in and retrieve them from variables.

Controlling the Flow of the Program

So far, our programs have only been able to run line by line (technically, statement by statement), in sequence from beginning to end. In this lesson we are going to learn several language constructs which allow us to control the order in which the statements in a program are executed.

First of all, what is a language construct?

A language construct (or a "control structure") is one of the allowable pieces of syntax that can be used within a program's source code. We've already learned two language constructs:

In PHP, the most primitive language constructs is a simple expression. The most basic or common expression is simply an assignment operation such as:
$x = 3;
Another PHP language construct is echo, which takes an expression (often a simple value) and turns its result into part of the program's output, such as:
echo "Hello";
Conditional Constructs

There are several forms of the if statement. The simplest form looks like this:
if (condition) outcome;
condition must be replaced with an expression resulting in a boolean (true/false) value. Frequently, a comparison operator such as ==, <, <=, >, >=, or != is used in this expression.

outcome should be replaced with the actual statement to be executed if and only if the condition is found to be true.

For example:
if ($x == 3) echo "Three!";
The value of $x is compared with 3, and if they are equal, the result of the expression is true. If the result is true, the outcome part of the if statement is executed, otherwise nothing happens and execution proceeds with the next statement.

Often, we wish to execute a whole sequence of commands based upon a certain condition. To do this, we may use a compound statement for the outcome part of the if statement.

A compound statement is another language construct which may be used anywhere in your program where a single statement would ordinarily be permitted. A compound statement is formed by enclosing statements within a set of curly braces. The curly braces and all of the statements which are contained therein are treated as if they were a single statement.

The if statement and a compound statement may be combined like this:
if ($x == 3) {
   $x =4;
   echo "This is a compound statement to inform you ";
   echo "that the value of $x was 3, but has now been changed to 4.";
}
Although the purpose of a compound statement is to combine several statements into one, it is perfectly legal to make a compound statement that contains only a single statement inside of it. I, along with many other sources, recommend always using the compound statement braces whenever writing out an if statement (as well as when writing out most of the other language constructs which you will be learning later.) The reasons for always writing them are to improve readability, and to make it simpler to adjust the program later because there will already be a place ready to insert additional lines of code.

The if statement has other forms as well. The next one we will learn is the if/else statement:
if (condition) outcome; else alternateOutcome;
With braces, this looks like:
if (condition) {
    outcome;
} else {
   alternateOutcome;
}
Technically, you may choose to omit the braces on either one of the two outcome clauses while including them on the other, although once again, it is my recommendation to always use them:
if (condition) {
   outcome;
} else alternateOutcome;

The if/elseif statement:

Sometimes it isn't a question of doing one thing or the other, but rather, a series of several possible outcomes, based upon different conditions.
if (condition) outcome; elseif (secondCondition) secondOutcome; else alternateOutcome;
Or, with braces:
if (condition) {
   outcome;
} elseif (secondCondition) {
   secondOutcome;
} else {
   alternateOutcome;
}
You may have as many elseif sections as you wish. They are tested in order from top to bottom, and only the first matching condition has its outcome executed. If none of the conditions are true, the alternate outcome listed in the else clause is executed. The else clause, however, is optional. If omitted, and none of the listed conditions are matching, execution will simply continue with the statement following the entire if/elseif structure.

There is one other Conditional Construct which we will cover in a future lesson.

Looping Constructs

Sometimes we want something to happen more than once. That's what a loop is for. There are several types of looping constructs available in PHP, but in this lesson we will cover only the one with the widest range of usefulness:

The While Loop

The while loop looks like this:
while (condition) loopBody;
If the condition is true, the loopBody is executed. After this, the condition is checked again, and if it is still true, the loopBody is executed again, and so forth, until the condition is found to be false. If the condition is never false, an "infinite loop" may be created and the program will have to be forcefully terminated in order to get it to stop.

You may notice that this is just like the basic if statement, except that instead of executing the outcome only once, it continues executing the provided statement(s) until the condition has become false. As with the if statement, the loopBody should probably be written as a compound statement for clarity. Here is a sample of a while loop in action:
$x = 10;
while ($x > 0) {
   echo "Looping!\r\n";
   $x--; // decrease the value of $x by 1
}
This loop will echo the message Looping! ten times before stopping.

That's it for now!

Next Post: I/O

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

Thursday, May 19, 2011

PHP Lesson 1: Hello World

PHP as a Programming Language

First, I need to explain that I'm teaching PHP as a programming language. When PHP was first designed, it was a simple collection of add on tools designed to spice up your personal home page. In fact, Personal Home Page is where the name PHP originally came from. Since then, it has transformed like a caterpillar into a butterfly to become PHP: Hypertext Preprocessor, and while it is still focused on HTML, I believe it to be a very capable language for all sorts of tasks.

What We Aren't Doing: If This Part Doesn't Make Sense, That's OK!

Classic PHP usage involves putting small snippets in the middle of a page of what would otherwise by HTML code, for example:
<p>This is a piece of HTML with a snippet of PHP thrown in to show you that today is <?php echo date('l'); ?></p>
Enclosing small amounts of php code within the <?php ?> delimiters allows PHP to be blended in with an otherwise ordinary .HTML file. But in these tutorials, we won't be using PHP in this way at all. We are going to install the command line version of PHP, and start our source code with the opening <?php tag, but that's it! That tag will never close, because we aren't going to be sending output to a web browser as HTML, we are going to be outputting plain text that we will work with directly from the command line.

Preparing Your Computer to Run PHP

Whether right or wrong, I'm making the assumption that you are running Ubuntu Linux as your Operating System. This is the only part of these lessons where this will make a significant difference, and I'm honestly just too lazy to write out instructions for other platforms right now. PHP is VERY cross platform, however, and if anyone would like to write out corresponding instructions for other platforms in the comments on this post, go for it!

Bring up a Terminal (Applications > Accessories > Terminal) and enter the following command and press ENTER:
sudo apt-get install php5-cli
Even though this isn't a Linux tutorial, I will break down what this means. sudo means "super-user do", which elevates your privileges to administrative level and runs the following command. apt-get install is the command used to install a package, and php5-cli is the Command Line Interface for the latest version of PHP in the 5.x series.

After pressing enter, you will be asked to type your password. As you type it, you won't see anything, but just trust that it is working, then press enter. You will be asked if you want to continue, press Y and enter. Wait while the installation takes place.

Now, we need to make a folder to store our work in for this series of lessons. You're probably already sitting in your home folder. Look at the command prompt and see the ~$ at the end. The ~ is Unix shorthand for "my home folder." Type the following command and then press enter to make a directory called bitslapped, or whatever other name you want to use (just remember to replace the directory name in all future references as well...)
mkdir bitslapped
On the majority of Unix and Linux file systems, folder and file names are case sensitive, so be consistent with how you capitalize if you choose to capitalize the folder name at all. Also, to avoid complications, please don't use folder names or filenames with any spaces in them for the material in these lessons, even though they are technically legal.

Getting Into Your Folder

In order to get into your folder to begin working, this time, and in the future when you open another instance of the terminal, you will need to issue one of the following commands. From now on, when at the terminal prompt, you should always press enter after typing each command and I shouldn't need to tell you to do that any more:

If you are already in your home directory (prompt ending in ~$)
cd bitslapped
Or, if you are somewhere else:
cd ~/bitslapped
If this is done correctly, your prompt will change so that it ends in ~/bitslapped$

We are going to be using two commands repeatedly throughout these lessons, so make a note of these:

To create or edit a file:
nano filename.php
Replace filename.php with the actual filename we're working with.

To have PHP run a program after we've saved it:
php filename.php
For now, use nano to create a file called hello.php by entering the following command:
nano hello.php
Whenever you run nano, if you get an error about nano_history permission denied, just ignore it and press enter. It's not a big deal. When nano opens, you will see a bar across the top of the terminal that says GNU nano (version number) File: hello.php and at the bottom of the screen you will see the [ New File ] indicator, as well as a list of command shortcuts.

When reading nano shortcuts, the ^ means to hold the "Control" or "Ctrl" key, and M- means to hold down the "Meta" key, which on a PC keyboard is the key labeled "Alt" on the left side of the bottom row.

Your cursor is at the upper left of the new text file, so go ahead and enter the following program code, exactly as shown here:
<?php

echo "Hello World";
Once you've entered the above code, press Ctrl+X to exit nano. It will prompt if you wish to save. Press "Y" for Yes and you will be prompted for the filename. It will already have the filename you specified on the command line written in, and if you are still happy with this name (hello.php) just press ENTER to confirm it, and you will be dropped back to the command line.

Now, use the following command to test the program you just wrote:

php hello.php
If everything worked as expected, you will see an output of Hello World followed immediately by the command prompt. There won't even be a space in between. It'll just be mashed together on the same line. Well, that's what we told it to do, but that probably isn't what we wanted. So, we need to edit our program to change this. Re-enter the nano command which can be easily done by pressing the up arrow twice to go thru your command line history, then press enter. Change the program to look like this. nano doesn't support the mouse for editing or moving the cursor. Deal with it, you're a programmer now. The keyboard is more efficient anyway, so use those arrow keys to get to the right place and make the necessary addition:
<?php

echo "Hello World\r\n";
Save it using the same steps as before: Ctrl+X, Y, Enter, then run it again by going thru the command line history to find the php command you previously typed: Up, Up, Enter.

This time you should get Hello World on a line all by itself, and then a separate line containing a new command prompt.

Don't worry about why we put \r\n at the end of our message yet, we will cover that in the next lesson.

So far you've learned how to enter the source code for a program, save it, go back and edit it, and run the program through PHP to see what it does.

Now, I will teach you a few things about what you've entered:

Every php source code file we write will begin with a line containing the magic characters <?php which tell the PHP interpreter that this is indeed a chunk of source code written in the PHP language that it should be able to process.

The command echo means to output the parameter which follows to the "standard output" which in our case is the terminal window screen (also known as the console.)

Because we are specifying a piece of text (called a string) as a parameter to the echo command, we enclose it in quotes. The quotes tell PHP to treat it as text instead of trying to interpret it as another command, as a mathematical number, or as the name of a variable. In PHP, you can use either "double" or 'single' quotes to enclose a string, but backslash codes like \r\n are only allowed within "double quoted strings."

Because some PHP commands can be quite lengthy and may take multiple lines to write out, PHP uses the semicolon character to mark the end of each statement. (A statement is the computer-science term for a single unit of executable code, it means basically the same thing as a "command", and includes any or all parameters that go along with the command.)

Next Post: PHP Expressions & Operators.

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.

Friday, May 13, 2011

Deciding on a Learning Language

I work at a computer center and we do tutoring and classes. I've recently taken on a new programming student and have put some thought into what language I should help her learn first. I've seriously considered C, C++, Python, Ruby and PHP.

First Consideration: Usefulness

In terms of usefulness, I consider Python to be the best choice. It is capable as a web language, a shell scripting language, and also for developing serious GUI applications. It also has very wide cross-platform support, a large community of developers online, and is a live language which is still being actively maintained in both a 2.x and 3.x branch.

Second Consideration: Syntax

I favor the syntax of PHP because it is very close to C syntax, and most modern languages are based upon C syntax in one way or another. This would imply that I also favor the syntax of C, and I suppose that is true. I am bothered that PHP requires an opening php tag at the top of each source file, and this is evidence that I am trying to use the language for something for which it was never designed. I believe there is too high of a barrier to using C for keyboard input and console output (a common task for beginning programmers) mainly because of its poor string handling, and because of this I went looking for other options more serious than PHP. Something about Python's syntax grates against my nerves, and I can't quite figure out what it is. (For the record, I don't mind the use of white-space to define blocks, which is unique to Python. I think it is pretty & clever. The only downside I see is potential trouble sharing code online because sometimes when code is copied and pasted via email, blog, or forum, it tends to get mangled and all the lines become left-aligned in the process.)

Third Consideration: Science?

I think either C or C++ would be a good first language because I believe there is value in learning a statically typed language so that the manner in which the computer stores values in memory can be better understood. This may be an antiquated idea to worry about, however, since in practice it may not be necessary to worry about such things any more. Also, I believe the philosophical concept of data types can be acquired just as easily by learning a database system such as MySQL.

Conclusions?

I'm unhappy with the options, but I have decided it would be reasonable to try to teach both PHP and Ruby. I have started with PHP because it is the language I am most intimately acquainted with, although I see Ruby as the more elegant language of the two.

I wish they were not both so scripty and dynamic. I like those properties in a language I'm going to use on a daily basis, but I think there is value in learning something more strict as well.

I wish there were more options available that also fall into the "useful" category.