Monday, 30 September 2013

Teething problems.

Well, after the confusion over my time table for the MSc Computing at Birmingham City University, I find myself in a nightmare situation of having to study Databases again; a subject that I don't get on with, that is confusing and much too high brow for me.

On Friday afternoon, just before leaving work, I discovered that the Database for Enterprise was scheduled for Monday morning at 9am. This was obviously short notice (especially for my employer), and to add insult to injury, the lecturer has not yet turned up nearly 30 minutes after the lecture was due to begin. I hope that this is teething problems, but with the lost time already (as there wasn't a lecture last week apparently), it's looking increasing unlikely that this will be a module that I'll pass because there simply won't be enough time left to cover everything that I need to know if we're running two weeks behind the proposed schedule, especially as I don't have access to the teaching material associated with this module.

Thursday, 26 September 2013

Now linked.

If you're reading this through BCU Moodle/iCity or whatever it is and wondering how I got so many posts, well I linked my Moodle blog to my Gaming and Technology blog. Most impressively, considering how useless the SharePoint interface usually is, it actually works! Oh, and you may have just got a lot of SPAM to your bcu mail account - sorry about that.

Anyways, today was my first lecture on the MSc Computing, and it's my favourite subject too - computer programming and software development. I'm really going to enjoy this C# stuff I think.

I emailed the lecturer Steve about a site which goes some way to explaining how computers do mathematics, and why you may end up with rounding errors - the link is floating-point-gui.de, and I recommend it for all budding developers. Although this sort of thing may go beyond the scope of the module, if there's any interested programmers and developers who want to chat about more advanced programming topics then just nudge me. Whatever my Uni ID says, I use my middle name (just to confuse everyone) - don't be shy as I don't usually bite.

Hello World... again.

Yet again, I find myself a student. This time, it's at the Birmingham City University, and - oddly enough - I'm studying MSc Computing.

Today was my first lecture: Systems Development, or more precisely, C# Programming, and even though it's a Masters, there's still the need to go through the print "Hello Mum"; or whatever to get the basics of the language. Thankfully, I had some writing to do though, so I sort of did that during the lecture. So, look out for news of a Pitfall clone for the Commodore VIC 20 and some ZX Spectrum and Commodore 64 news in a Micro Mart issue soon.

Friday, 14 June 2013

Working with percentages

I wouldn't say that I'm the best mathematician; if I'm being generous, my skills in the maths department is somewhere about average which isn't always a good place to be for a programmer. But what I lack here I make up for in understanding of how computers work and how to program them, and this is what acts as a stabiliser against the wrath of BODMAS and such like.

So, I've been working on a project for a client which in part has to work out percentages of a price, like adding VAT levied by the Government on saleable goods. Now, this is actually the easy bit. VAT, at the time of writing, is 20%, so if an item costs £100 without it, that item will be £120 including VAT. So, writing the code for this is simple: take the current price, work out 20% and add that to it. Or, multiply the current price by 1.20, which does the same thing.

Writing the code for this is easy, in a C-like language, it would be something like:

// assuming £80.00p
float price = 80.00f;
// This is a quick way to add VAT @ 20%
float priceWithVAT = price * 1.20f;
// So...
printf( "Price ex-VAT: %.2f", price );
printf( "Price with VAT: %.2f", priceWithVAT );
  

Great! Assuming the VAT rate will always be 20%, this will always work. But not long ago, VAT was at 17.5%, and before that, which dropped temporarily to 15%. Now, let's say that you want to work with different percentage rates, or the rate unexpectedly changes. Something like the following will work:

/**
 * A quick demonstration of working out
 * percentages using C will probably work
 * on all other problem-orientated
 * languages.
 *
 * Written with Code::Blocks, tested on
 * Windows 7 and cmd.exe
 *
 * @Author:  Shaun B
 * @Version: 1.0.1 - 2013-06-14
 * @Todo:    Look into floating point guides and why
 *           there are rounding errors
 */

#include <stdio.h>
#include <stdlib.h>

// Function prototypes:
int main();
float percent (float pc);
float taxToAdd (float number, float percent);

// Variables:
float taxRate = 20.00f; // ie VAT, PAYE etc...
float percentage = 0.00f;
float taxToPay = 0.00f;
float priceWithTax = 0.00f;

int main()
{
    float originalPrice = 59.99f;
    unsigned char pound = 156;

    percentage =
        percent (taxRate);
    taxToPay =
        taxToAdd (originalPrice, percentage);
    priceWithTax =
        originalPrice + taxToPay;

    printf(
        "Tax rate set to: %.2f\%%\n", taxRate
    );
    printf(
        "Original price of goods less tax: %c%.2f\n",
        pound, originalPrice
    );
    printf("Tax on goods: %c%.2f\n", pound, taxToPay);
    printf(
        "Total payable: %c%.2f\n", pound, priceWithTax
    );

    printf("Fin. Press any key.");
    _getch();

    return 0;
}

float percent (float pc)
{
    return (float)pc/100.00f;
}

float taxToAdd (float price, float percent)
{
    return (float)price*percent;
}
  

Things should be fairly self-explanatory here. This example means that if your tax rate changes, you only have to change one variable rather than tracing all of the instances of *1.20f in your source code. This makes it easy to set percentage rates for other taxes, levies or fees that a client may encounter. The only problem now is what to do with the third decimal place, say if something works out to be £17.8555 with fees or taxes added? I think things are usually rounded up though.

Note that the £ sign doesn't appear on my computer here - all of the documentation online says that it should be 0xa3 (or 163 in human), but I found it to be 156 (or 0x9c in hexadecimal) on this Windows 7 machine.

Wednesday, 10 October 2012

The problem with while loops in PHP.

As a programmer who is rather fond of the language C, I tend to use a lot of while loops. These are great as in C one or more is true and zero is false, so if you are writing a simple Space Invaders clone, you would logically have a variable of type int called lives, so:

int lives = 3;
  

and in the game pump, you'd simply have:

void gamePump( void )
{
     while( lives )
     {
          // Do the game routines
     }
     gameOver();
}
  

So, when lives is zero, it'll call the routine or function or method you've called gameOver, and logically return to the title screen after that.

We can use the same logic with PHP, of course, but let's say this time we want to echo out an array of names. You'd do something like:

$names = array(
    'Dave',
    'Eric',
    'Zach',
    'Andrew',
    'Lisa',
    'Andrea',
    'Richard'
);
$index = 0;
while( $names[ $index ] ) {
     echo $names[ $index ] . PHP_EOL;
     $index++;
}
  

This will return an error, which is why the foreach command is there, so the same code in foreach would be:

$names = array(
    'Dave',
    'Eric',
    'Zach',
    'Andrew',
    'Lisa',
    'Andrea',
    'Richard'
);
foreach( $names as $name ) {
     echo $name . PHP_EOL;
}
  

Okay, so the error is solved. But if you wanted to use a while loop specifically, like in C, you'd have to null-terminate the array. In the top example above, you should:

$names = array(
    'Dave',
    'Eric',
    'Zach',
    'Andrew',
    'Lisa',
    'Andrea',
    'Richard',
    null
);
// etc...
  

This works fine if you don't want to sort the array alphabetically. If you do use the sort command, you'll need to use the foreach method above, as the first entry after a straight sort (key zero) will be null.

Monday, 24 September 2012

Octal.

If you've ever worked with machine code or assembly, or even C or C++, you will have come across binary and hexadecimal. Lesser-used number systems are binary coded decimal and octal. I've just had a quick discussion on Facebook, in which I quickly converted a number in hex into its' binary equivalent. This is easy to do, and when you know how, the same principles apply to converting a binary number to octal, although you group together every three bits, rather than every four.

But who uses octal anyway? I was asked by someone perhaps being a little complacent and because octal isn't commonly used any more by any programmer under the age of 40 (at a guess).

Not using octal doesn't present an immediate or obvious problem as most people work with decimal unless they have to use anything else. But what if you were interfacing with a database, calling a users phone number, for instance, and you cast it incorrectly? This is exactly what I did. I'll explain more about this in a mo, but first, let's look at hex and decimal.

Hex numbers begin with 0x (zero-x) and counts 0 - 15 for each place, for instance:

// 32-bit RGB value read as AARRGGBB
#define   COLOUR 0xff071dee

and with binary, you'd use a 0b prefix, and each place is either zero or one. Decimal is how you'd use it in the real world, with no leading character, but octal simply starts with 0 (zero), and here is where the problems can begin.

For those of you old enough, you may remember that, once upon a time, all telephone numbers started with zero. My area code was 0606. Inexplicably, British Telecom (as it was known at the time) changed this for no apparent reason to 01. Now, a friend of mine vented his frustrations about this. Why? What was the point? He enquired about this quite a lot, reporting back through his fanzine 8 Bit, as it seemed to be a change just for the sake of it, and no one was providing a good explanation.

Thinking back now and with the benefit of computer science-type study since, could it be that some computer systems were being tripped up by the leading zero, especially if the rest of the number looked like octal to some server somewhere? Imagine if you had a taxi business in the Greater London area, and chose a very easy to remember number like 071 777 7111. The octal value of this is very different to the decimal one, so adding the 1 immediately after the zero could have been an attempt at a remedy from it being automatically cast to octal and therefore showing a different decimal value after the casting. Well, maybe.

Could it also be now that all phone numbers start +44 nowadays because of this known problem?, especially as most mobile numbers start 07. Well, a couple of weeks ago, I was working with a young guy at Metapps on some PHP basics. He was doing a short works experience while in the local area, and was due to travel back to London soon, so we had to squeeze a lot into a short space of time.

In the task that we were working through, we were adding data entries to a database and calling it back. The example was someone's name, address and telephone number, and I put an example for the latter field of 07777777777, and called it back using some basic PHP code (well, inline SQL to be more exact), storing the retrieved data in a variable called $phoneNumber. PHP is very loosely typed and handles variables, as far as I can tell, very safely. There's really no need for leaky memory to be crashing a server, is there? But I had my C head on, and I cast the number to type int. When I echoed out the variable, I got a very strange result.

Luckily, the problem was quickly resolved by using the +44 prefix, and therefore dropping the leading zero. Remembering that I was using PHP, I also dropped the casting to type integer. I then went on to explain to the young 'un about how computers store numbers, and how compiled code and interpreters these 'scalar types' them from an area of memory, a file or a database, and how different prefixes can affect the value, with a leading zero being the prime example stating "this number is octal".

So, who uses octal anyway? Well, the question shouldn't be who, but what technologies use octal... and PHP, along with C and C++ are definitely included there, along with, I imagine, Java. Sometimes, it's good to know these things.

Thursday, 8 March 2012

6502 programming.

The latest issue of the excellent Commodore FREE is out (issue 59), and is available at www.commodorefree.com. In it is the second part of my 6502 programming tutorials that I wrote for Micro Mart (issue 58 has parts one to four, followed in this issue by five to eight), for those who may be interested in learning a bit of machine code on the Commodore 64.

I'm really pleased with the number of reads of my Z80 tutorials here, so hopefully this will prompt a similar number to read Commodore FREE perhaps for the first time. Feel free to ask any questions here (including code examples), and I'll do my best to answer you.