Computers allow kids to better understand and learn math

Back in 2010 at TED talks, Conrad Wolfram  spoke about math in schools, and teaching kids real math with the help of using computers (Conrad Wolfram: Teaching kids real math with computers) this video was to me very interesting, so I decided to do some study, and also decided to write this article to present some of my findings, ideas and results.

 

Teaching math in school

Mathematics in school is simple when you first time start doing math and learning it. However, as you grow older, in school you also study higher levels of math, and these levels become challenging in some cases. There are three factors that impact the way you learn math, these are:

 

  1.   Your ability to quickly calculate and play with numbers
  2.   The way your teacher is teaching math during a math session
  3.   Your own interest in learning and understanding math

 

Note: Above I only included three factors, but there are a lot more factors that impact the way we learn math.

 

Math levels

The math is divided in levels, and each level is unique. Basic level is where we all start, and that is obvious, nobody can start at the last level, even Albert Einstein had to start from basic level.

 

  1. Basic Math
  2. Pre-Algebra
  3. Algebra
  4. Geometry
  5. Algebra 2
  6. Geometry 2
  7. Trigonometry
  8. Pre-Calculus
  9. Calculus
  10. Advanced Calculus

 
There are probably a few more levels I haven’t included here.

 

Computers are great calculators

Personal Computers (PCs) are great calculators and are some of the fastest calculators in the world; of course a modern calculator uses the same technology, the Central Process Unit (CPU), one modern and much known CPU is the Intel® processor. The Arithmetic Logic Unit (ALU) is one of the essential and key features in a CPU, which allows the CPU to perform arithmetic operations Addition, Subtraction and so one. Beside the arithmetic operations, the ALU allows the CPU to perform basic logical operations such as AND, OR, NOT, XOR (exclusive or) and so one.

 

Humans have created a set of CPU instructions that can be used to tell the CPU what to do; this language is called Assembly (ASM). ASM has been around for a long-time, and is common in many areas in the software world. ASM is still used to build boot loaders in Operating System (OS) development. However, the computer sees everything in 1 and 0 or in binary form, but I would like to demonstrate how a CPU-instruction in ASM will add two numbers, I will be using C++ programming and perform inline ASM.

 

I will be using the x86 (32-bit) CPU registers to store data. The EAX, EBX, ECX and EDX are the four general registers. I will keep this very basic, with a lot of details.

 

 

This code may seem advanced, but is quite easy to understand, okay, I’ll explain. Let’s examine what really happens, we jump to the int declaration.

 

i. I start by declaring three int variables they get a default value zero.
 

int valueA, valueB, result = 0; 

 
ii. Jumping one line, valueA equals 5 and valueB equals 10.
 

valueA = 5; 
valueB = 10; 

 

iii. Then we enter the inline code of x86 CPU assembly instructions, we use the MOV instruction to move data from valueA to EAX, and we move data from valueB to EDX (Figure A explains the first move).

 


Figure A: The MOV instruction makes EAX as the destination for the data variable valueA contains. This is exactly the way the MOV instruction moves data, which can be defined like this: MOV destination, data.
 

 

iv. Then we perform addition, by using add eax, ebx which means EAX = EAX + EDX so we store the end result in EAX register.

 

v. Next, we store the data which EAX contains in the result variable, and finally we XOR (clear) the EAX and EDX registers.

 

This is another example of how a CPU performs arithmetic calculations. I am glad I was able to provide a demonstration and explanation regarding this.

 

Programming helps understanding and learning math better

Mathematics appears to be a great subject, but as you move further and begin learning and experimenting with higher levels of mathematics things can get really messy. When   equations and formulas including different theories and rules are involved in mathematics, this will directly make things harder for anybody. However, a key solution to better learning math rules, theories, equations, and formulas is by learning basic programming. If every child started learning basic programming at the age of 10 we would never experience math issues in school, no matter how advanced and complex the math would become at least 90% percent or more of all the students would hopefully pass the test, all this thanks to programming. Children do not need to learn Object Oriented Programming (OOP), they only need the basics (understanding code, data-types, and logic if-else statements), and to learn how to program the application so it can receive input (argument) and provide output (print to the screen) nothing else.

 

Here’s how programming helps students understand and learn math faster and better. If you know programming, you can make a function in your program that calculates for example the slope of a line. But to make this function you have to learn and understand the formula, the rules and how it is used correctly the mathematical way. However, I will provide two examples, one which is very basic and the other one which is a bit complex, but yet easy as well.

 

Programming example 1:
Build a program that calculates total price per mile a taxi driver, drives a person. Remember: The taxi company has a fixed price which every customer has to pay the fixed price (f) which equals to $20 USD is added to the price $4 USD / mile.

 

We have three things to keep in mind:

 

  1. Price per mile.
  2. How much a customer has to pay?
  3. Remember that 1 Mile equals 10 km

 

Now this is going to be very simple. But it will allow any student to better remember and understand how this works.

 

This is the equation or formula which I have setup:

 

 

Variables:
T = Total cost.
P = Price
F = Fixed price
X = Mile(s)

 

Calculation by either hand on paper or writing it in word like this may seem like a long calculation, but is very short.

 

T(x) = f + px
T(5) =  20 + (4 * 5)
T(5) = 20 + 20
T(5) = 40

 

Here’s the code in C++:
 

int T(int x); 

//$4 USD per mile. 
int p = 4; 
//$20 USD.
const int f = 20;  

void main()
{
   int Total = 0; 
   Total = T(5); //5 miles = 50 km. 
   cout << "The customer has to pay: $" << Total << " USD" << endl; 
   cout << "" << endl; 
   system("pause"); 
}

int T(int x)
{
    return f + (p * x);  
}

 


Figure B: The computer did the calculation, but I had to program the software so it can do what I want it to do. This allows me to learn more about the rules, and allows me to determine whether my equation or formula works.

 

 

Programming example 2:
In this second programming example, we will be looking at the linear equation, slope and m interception with the Y-axis.

 

We have two things to keep in mind:

 

  1. Remember the equation: y = mx + b
  2. Remember that b = y-axis  intercept.

 

 

Variables:
M = slope
B = Y-axis intercept
Y = The total value

 

 

 

Find M-value:

 

 

 

m = y2-y1/x2-x1
m = (3-2)/(2-1)
m = 1

 

y = 1x + b
y = 1x + 1
y = (1 * 2) + 1
y = 3

 

Test our calculation:
3 = (1 * 2) + 1

 

Here's the code in C++:
 

double Slope(double y1, double y2, double x1, double x2);  
int Y(double m, int x, int b);

double m = 0; 
int x, y, b = 0; 

void main()
{
    cout << "Find the Y-axis interception value: "; 
    cin >> b ;
    cout << "\n" << endl; 
    cout << "Calculating..." << endl;
    m = Slope(2, 3, 1, 2); 
    y = Y(m, 2, b); 
    cout << "Y = " << y << endl; 
    cout << "" << endl; 
    system("pause"); 
}

//Note: Slope function works only when two known points are passed in, 
//single point is not supported by this function. 
double Slope(double y1, double y2, double x1, double x2)
{ 
    y2 = y2 - y1; 
    x2 = x2 - x1;

    if(y2 == 0 || x2 == 0)
    { return y2; }
    else{
      return y2 / x2; 
    }
}

int Y(double m, int x, int b)
{
    return (m * x) + b; 
}

 


Figure C: Our program calculating the slope and the Y for us.

 

Conclusions

I personally think that the nation that first applies "teaching programming" in school, and I mean children start doing basic programming at the age of 10 will increase their economy and produce a lot of smart people. However, this is one of the reasons governments all over the world shall demand that this becomes a reality, because programming covers math, logic thinking and much more. Mathematics has not been an easy subject in school, and that is because of the levels and each individual's ability to play with numbers, to understand equations etc. But for the coming future, I think programming will play a key role in combating the math problem we see in schools in many parts of the world. The time to change is now, so demand for this change today, for a better tomorrow.

 

Additional information and resources:
Albert Einstein Biography: http://nobelprize.org/nobel_prizes/physics/laureates/1921/einstein-bio.html
The Arithmetic Logic Unit: http://www.windowsnetworking.com/articles_tutorials/arithmetic-logic-unit.html
Linear Equation: http://mathworld.wolfram.com/LinearEquation.html
Slope: http://mathworld.wolfram.com/Slope.html
Slope-Intercept Form: http://mathworld.wolfram.com/Slope-InterceptForm.html

 
 

The Power of a Virtual School on the Internet

In August 2004, Salman Khan (a.k.a. Sal Khan) a former hedge fund manager, began helping his niece, Nadia, with her math homework. Sal began helping Nadia, by doing videos about different math problems, and how to solve them. Sal uploaded all the videos to YouTube™, and as the time moved one, Sal uploaded more and more videos. Suddenly he had uploaded around 2K of videos, and he became famous and created a virtual school named Khan Academy. However, in this article I will be talking more about this fantastic idea, I will also provide more details about Khan Academy, and the benefits of having it, and the bad things regarding it.

 

The Khan Academy
Khan Academy is a non-profit (or not-for-profit) organization, with the mission to provide a free world-class education service to anyone, anywhere at any time on earth. The Khan Academy now provides around 2400 around 3500 videos, and consists of a software program which allows anybody to test their skills. The greatest part is the opportunity to be able to test your math skills after watching one or two videos, because you then know exactly how much you’ve learned by watching those videos see Figure A.

 


Figure A: A video at Khan Academy covering Simple Equations
 

The software which is built-in into this service is used for practice purposes, and it is a very good option. The software consists of a database, badges and points, and a knowledge map (Figure B).

 


Figure B: The map is produced using Google™ Technology, and is a very colorful map. The map
provides different levels, for example: Addition, and Addition 2, 3, and so one. Each of these
destinations, provide unique questions which allow the user or a student to put their math skills to the test

 

The math-games are fun, every time you succeed you’ll get a positive smile, and every time you fail, you’ll get the negative smile, very straight forward (Figure C). However, another very cool thing is that while playing, you can decide to go and watch a video related to that math level (Figure D).

 


Figure C: Playing subtraction level 4

 


Figure D: You can directly navigate to a video that covers information about that specific math level, and problem
 
Note: You can still go back and continue with the current level in the game, without losing everything.
 
The point and badges system however is really nice. Every time you complete a test in the knowledge map, and every time you watch videos for an amount of time (hours) you’ll get points (Figure E).
 

Figure E: My account, I have 101,365 points currently
 
The badges are awesome, and they exist in different types, there are six types, Meteorite, Moon, Earth, Sun, Black Hole and the special Challenge Patches (Figure F).
 

Figure F: Example of the badges, those are my earth badges on Khan Academy
 
There are so many things you can do at Khan Academy, why wait when it is available for free just go to the official website http://www.khanacademy.org/.
 
Conclusions
People have been doing videos about all types of subjects, for example you have education videos which teach physics, math, chemistry and much more. Just visiting YouTube™ and searching for simplifying rational expression will give us over 2K in result, and you will find a lot of videos, different people have done that teach you how to simplify an rational expression. However the Khan Academy is very different, you have short videos with a lot of examples, and the voice in these videos is awesome, Salman is very good at speaking and explaining things. The entire idea and system with Khan Academy is really awesome, I personally like the way it is organized. This idea is also great, because Khan Academy can be reached by people all over the world however there is a down-side for those who do not have access to either a computer or Internet.
 
However, another thing that has been discussed very much in the Media, when Salman Khan appeared on the news, is the following question, Will Khan Academy replace ordinary schools? – remember this is like a virtual school available on the Internet. The clear answer is NO, and this is very obvious as students still need to do the tests, and teachers cannot be fired, just because someone invented the virtual school.
 
In addition, I personally think that Khan Academy can be used as an extra hand, in case you are home and you get stuck in a math problem which you cannot solve at that moment, because you do not remember how to apply a specific formula. Khan Academy will be your best hand in helping you to successfully solve the math problem, and learn it to the next time. However, a real school is still the best place, and I prefer that rather than going to a virtual school, but that is me.
 
Additional information and resources:
The Official Khan Academy website: http://www.khanacademy.org/
About Khan Academy: http://www.khanacademy.org/about
The Khan Academy Channel on YouTube: http://www.youtube.com/user/khanacademy
 

Windows Phone 7: Using GeoLocation API and Consuming Web-Service with C#

Hey! I am back with a third post on WP7 Development with C#. This time we’ll be making a Windows Phone 7.1 application that uses the GeoCoordinateWatcher class and consumes one web-service.

 

  1. Begin by launching Microsoft Visual Studio 2010 on your computer, click File, next New and select Project.
  2. From the Installed Templates Pane, expand Visual C# and select Silverlight for Windows Phone.
  3. From the Project Templates List in the middle select Windows Phone Application. Name the project whatever you want I named mine “geolocationsample” and click OK.

 

Microsoft Visual Studio 2010 will now generate all the project files for us to use. Before we continue, start by dropping two UI components from the Toolbox, one Textbox and one Button. For the button1 set the text to “Find Me” and save. Make sure it looks as shown in the screenshot below:

 


(Click to view larger)

 

Next, right-click button1 and select Properties, from the Properties panel, select Events and locate the Click, once located double-click it so that Microsoft Visual Studio adds button1_Click event to our code. Leave it for now; we’re going to write code for that later.

 

To be able to use the GeoCoordinateWatcher class we need to add another assembly reference to our code, you do this from the Solution Explorer, by right-clicking References and selecting Add Reference. Find the System.Device reference and click OK.

 

 

Don’t forget to add the namespace inside the code as well.

 


Time to write code for the button1_Click event, you can just copy the code I’ve written below:

//Setup two variables
double latitude, longitude = 0.0;  
//Create an instance of the GeoCoordinateWatcher class
GeoCoordinateWatcher gwatcher = new GeoCoordinateWatcher();
//Store all the Position information inside PositionNow 
var PositionNow = gwatcher.Position;

/* 
   New York, United States
*/
latitude = 74.0064;
longitude = 40.7142;


/* 
  If the location is NOT unknown 
  then retrieve Latitude and Longitude 
  dynamically.
*/
if (!PositionNow.Location.IsUnknown)
{
     latitude = PositionNow.Location.Latitude;
     longitude = PositionNow.Location.Longitude;
}

The above code will compile fine without syntax errors and/or other errors. However, for us to retrieve location information i.e. for example New York, United States latitude = 74.0064, and longitude = 40.7142, we have to consume some web-service that does this for us.

I’ve decided that I will use the Microsoft Research Maps (http://msrmaps.com/webservices.aspx), the TerraService (http://msrmaps.com/TerraService2.asmx), which provides an *.wsdl for Microsoft Visual Studio to read from XML, http://msrmaps.com/terraservice2.asmx?wsdl.

Copy this url = http://msrmaps.com/terraservice2.asmx. In Microsoft Visual Studio, right-click the project (In my case geolocationsample), and from the context-menu select Add Service Reference.


(Click to view larger)

In my project, I left the namespace name ServiceReference1 and clicked OK.

Note: If Microsoft Visual Studio reports Error: Cannot import wsdl:binding, then you’ll have to reconfigure the Service Reference to fix this, else IntelliSense will not find the namespace of the service.

To fix this, simply right-click the Service Reference, ServiceReference1 and from the context-menu select Configure Service Reference.

Uncheck Reuse types in referenced assemblies and click OK.


(Click to view larger)

Now, let us go back to the button1_Click and consume the Web-Service we’ve referenced, copy the code below and paste it before the closing curly bracket (}) in the button1_Click event.

//Create an instance of the TerraServiceSoapClient class 
ServiceReference1.TerraServiceSoapClient tsclient = new ServiceReference1.TerraServiceSoapClient();

//Add an event handler
tsclient.ConvertLonLatPtToNearestPlaceCompleted += new EventHandler(tsclient_ConvertLonLatPtToNearestPlaceCompleted);

//Pass latitude and longitude and consume           
tsclient.ConvertLonLatPtToNearestPlaceAsync(new ServiceReference1.LonLatPt { Lat = latitude, Lon = longitude }); 

Since we’ve added another event handler (tsclient_ConvertLonLatPtToNearestPlaceCompleted), we need to write some code within it as well, copy the line below:

textBox1.Text = e.Result;


If you have done everything correctly, then you’re good to go, hit F5 to build and run in debug mode inside the Windows Phone Emulator.

In my Textbox it says: “7807 km NE of New York, New York, United States”, so it worked slightly with a fraction of error I guess, anyway.

To find more latitudes and longitudes, simply use Google.com, new york latitude longitude or Redmond, Washington, United States, Note: Redmond, Washington, United States, latitude = 47.674 and longitude = -122.12, anyway, good luck hope this worked for you.

(Click image to view larger)

If you have problems with this code sample, simply do this, from the Solution Explorer right-click the ReferenceService1 and from the context-menu select Update Service Reference, this will re-download all the necessary information, code and more for your app to consume the web-service.

Download attached C# code sample:
Geolocationsample.zip

Dijkstra’s Algorithm

The Dijkstra’s Algorithm created by Edsger Wybe Dijkstra (1930 – 2002) solves the shortest path problem, and is one of the most popular algorithms in computer science. In 1959, Dijkstra’s 3 pages long paper titled: “A Note on Two Problems in Connexion with Graphs”, was published in the journal Numerische Mathematik (1, 269-271). In this paper, Dijkstra proposed algorithms that help find shortest path between graph vertices in a graph. In most literature the Dijkstra’s algorithm is described as a greedy algorithm.
 
Dijkstra’s algorithm can be used to find the most low-cost path i.e. a cheaper way to transport an object to a destination from a source. However, before we use Dijkstra’s algorithm, let’s have a quick look on digraphs (directed graphs).
 
Directed graphs have oriented edges, where nodes are connected by these edges. A directed graph can be defined as a pair G = (V, E), V is a set of vertices, and E is the set of edges, see illustration below:
 

 
Now, with that covered let’s have some fun with the Dijkstra’s algorithm, shall we? Of course we will.
 
I’ll try to keep it simple, so I made a graph with paths from A to F, and each available choice has a cost, and we will chose the cheapest paths available, see graph below.
 

 
Once solved, it should look like this inside a table:
 

 
This symbol means infinity. In the last choice, I went from D to F, the cost was an additional +20, meaning that in total it becomes 100, and 100 is always better than infinity.
 
If something isn’t clear, feel free to send me an e-mail, via: http://www.itknowledge24.com/contact.php.
 
Let me explain furthermore, how the Dijkstra’s algorithm works? Dijkstra’s algorithm works by solving the shortest path problem, it does this by computing the shortest path from the source to vertices among the closest vertices available to the source. For the Dijkstra’s algorithm to work and operate normally, the edges should be non-negative, if however, negative edges exist, Dijkstra’s algorithm will ultimately fail because shorter paths cannot be obtained, resulting in EPIC fail. In simple and short terms, the algorithm works by keeping shortest distance between vertex (V) from the source in an array and iterating until solved.
 
In conclusion, the Dijkstra’s algorithm is used almost everywhere—for example, the algorithm is used in the following areas:
 

  • Traffic Information Systems
  • Mapping (Google Maps or other mapping services or software)
  • Routing Systems

 
 
References:
http://www.cs.utexas.edu/~EWD/
http://www-m3.ma.tum.de/foswiki/pub/MN0506/WebHome/dijkstra.pdf
 
For further reading, I recommend, MathWorld,
http://mathworld.wolfram.com/DijkstrasAlgorithm.html
and http://mathworld.wolfram.com/DirectedGraph.html
 

Windows Phone 7: Install Windows Phone 7.1 SDK

Welcome, to a Windows Phone 7.1 (WP7) Apps Development Series, I’ll be covering quite a lot about the WP7 and building different samples with C#.
 
However, before you begin make sure you have:
 

  • Microsoft Visual Studio 2010 SP1 Installed.
  • Windows Phone SDK 7.1 Installed.

 

Download: Service Pack 1 for Microsoft Visual Studio 2010
Download: Windows Phone SDK 7.1
 
Install everything. :)
 
Step 1: SP1 for Microsoft Visual Studio 2010
 

 
Step 2: Complete the Windows Phone SDK 7.1 installation, and check your Start Menu for new tools installed by the SDK
 

 
Step 3: Launch Microsoft Visual Studio 2010, and you’ll see new project templates added
 

 
Step 4: Create one sample, and hit F5 to launch it inside the Windows Phone Emulator
 

 
That’s it for this time…enjoy!
 

Math Is Fun: Geometric Sequences and Sums with C# and (Native) C++

Mathematics is really fun sometimes; however, what makes it difficult is that it is a fundamentally different way of thinking—for example, learning languages can be much easier than learning math.

 

Since I’ve been playing with geometrical sums and sequences I decided to try this out with some computer programming, so I wrote two methods in two different languages, one in C++ and the other one in C#.
 

I’ll be using the following geometric sum formula:

 

C#:

static double CalcGeoSum(double a1, double a2, int n)
{
   double k, sum = 0;
   k = a2 / a1;

   if (k <= 1)
       sum = 0; 
   else
       sum = (a1 * (Math.Pow(k, n) - 1)) / (k - 1);

   return sum; 
}

 

C++:

float CalcGeoSum(float a1, float a2, int n){
   float k, sum = 0.0;
   k = a2/a1; 
   
   if(k <= 1)
       sum = 0.0; 
   else 
       sum = (a1 * (pow(k, n)-1))/(k-1);
   
   return sum; 
}

 
It's simple to invoke this function in any of the programming languages, just invoke it and pass it the required arguments. See the example below:
 
Invoke in C#:

static void Main(string[] args)
{
    Console.WriteLine(Convert.ToString(CalcGeoSum(3, 18, 6)) + "\n\n");
    Console.ReadKey(); 
}

 
Invoke in C++:

void main(){
    float result = CalcGeoSum(3, 18, 6); 
    cout << result << endl; 
	
    system("pause"); 
}

 
The output when you compile an run one of these code snippets in debug mode will be:

Output in C#: 27993
Output in C++: 27993

 
For further reading, I recommend MathWorld,
http://mathworld.wolfram.com/GeometricSeries.html
 

Why Learn the Assembly Programming Language?

The Assembly programming language can be painful, not only the learning process, but keeping it up i.e. keep programming with assembly. Personally, I like the assembly programming language, because it allows the inner geek inside me to master i386 machines, and do a lot of funny things at the low-level.

 

Assembly is not only about writing the code and telling the Central Processor Unit (CPU) what to do, it is a lot more. To master assembly, one needs to master mathematics (to a level), hexadecimals (0-F), the binary language, and the understanding of bits and bytes.

 

So why should one learn the assembly programming language?

 

This question is interesting, and receives many different answers based on who answers it. Assembly is not usually needed these days, especially, when we have all of these free choices of high-level programming languages that build on the Object-Oriented Programming (OOP) principles.

 

To better master the knowledge of different parts of the computer machine, the assembly language can be worth learning. Some companies that produce PC games use some assembly to deal with graphics. Other companies use it for other purposes, like building Real-Time Operating Systems (RTOSs) which are deployed in various industries to control robots.

 

Since assembly is a low-level programming language, developers, engineers, and programmers in general have a better understand of what’s happening at the low-level thanks to the assembly.

 

In conclusion, if you feel and think that the assembly programming language is something for you to learn, go ahead by no means. However, if you think “this is nothing for me”, then please do not waste your time learning it.

 

Intel Architecture Software Developer’s Manual

 

Volume 1 , Intel Basic Architecture: Order Number 243190 , PDF, 2.6 MB.

Volume 2 , Instruction Set Reference: Order Number 243191 , PDF, 6.6 MB.

Volume 3 , System Programing Guide: Order Number 243192 , PDF, 5.1 MB.

 

I  highly recommended that you download the above manuals and use them as a reference.

 

Building Your Own Bootloader

I am one of those folks who are very interested in understanding how Operating Systems work, no matter if it is Windows, or Ubuntu (or other Linux distros), or MAC OSX. Building your own bootloader is a pretty easy thing to accomplish; however, I think it would be wise to explain the concept and the terminologies in this area.

 

Bootloader is a small program that is executed under boot up in 16-bit Real Mode. It is very small, in fact, it is only 512 bytes and it resides on the very first sector of a boot device. The bootloader is used to load more complex programs like an OS Kernel. The 512 byte bootloader code is stored with the Master Boot Record (MBR) and is loaded by the Basic Input/Output System (BIOS) via Interrupt (INT) 0x19 at 0x0000:0x7c00h. This is a standard sequence in booting for almost all x86 PCs, except that in some PCs it can be loaded to 0x7c00:0x0000h.

 

To be able to accomplish this successfully, you need the following tools installed on your computer machine:


  1. Notepad++ a freeware source code editor supports syntax color highlighting for all programming languages,
    as far as I can confirm it.
  2. Netwide Assembler (NASM) is a freeware assembler used to produce binary programs, or boot images.
  3. VMware Workstation (This one is not freeware), however, if you want a freeware I highly suggest Oracle’s VirtualBox.
    You will need a virtual machine to run this code one; I do not want you to run this code on your own machine.

 

Download:
Notepad++ (http://notepad-plus-plus.org/)
NASM (http://www.nasm.us/)
VMware Workstation (http://www.vmware.com/products/workstation/)
Virtual Box (https://www.virtualbox.org/)

 

Let’s build our own bootloader with assembly programming language. Open Notepad++ and created a new file, set the language to Assembly, and replace the content with the code below. Don’t be afraid, I will explain line-by-line below.

 

bits 16 ; 16-bit Real Mode
org 0x7c00 ; BIOS boot origin 

jmp main ;Jump to start main() entry-point 

;;;;;;;;;;;;;;
; Variables 
;;;;;;;;;;;;;;

Message db "Hello World, booting from low-level 16-bit...", 0x0 
MessageB db "Fisnik's own bootloader program written in x86 assembly language.", 0x0
AnyKey db "Press any key to reboot...", 0x0 

;Print characters to the screen 
Println:
    lodsb ;Load string 
    or al, al
    jz complete
    mov ah, 0x0e 	
    int 0x10 ;BIOS Interrupt 0x10 - Used to print characters on the screen via Video Memory 
    jmp Println ;Loop   	
complete:
    call PrintNwL

;Prints empty new lines like '\n' in C/C++ 	
PrintNwL: 
    mov al, 0	; null terminator '\0'
    stosb       ; Store string 

    ;Adds a newline break '\n'
    mov ah, 0x0E
    mov al, 0x0D
    int 0x10
    mov al, 0x0A 
    int 0x10
	ret

;Reboot the Machine 
Reboot: 
    mov si, AnyKey
    call Println
    call GetPressedKey 

    ;Sends us to the end of the memory
    ;causing reboot 
    db 0x0ea 
    dw 0x0000 
    dw 0xffff 

;Gets the pressed key 
GetPressedKey:
    mov ah, 0
    int 0x16  ;BIOS Keyboard Service 
    ret 

;Bootloader entry-code 
main:
   cli ;Clear interrupts 
   ;Setup stack segments 
   mov ax,cs              
   mov ds,ax   
   mov es,ax               
   mov ss,ax                
   sti ;Enable interrupts 

   ;Print the first characters  
   mov si, Message 
   call Println 

   mov si, MessageB
   call Println 

   call PrintNwL
   call PrintNwL

   call Reboot 

   times 510 - ($-$$) db 0 ;Fill the rest of the bootloader with zeros 
   dw 0xAA55 ;Boot signature

 

That’s a lot of code, huh? Well, don’t worry, I will explain this line-by-line to make sure you understand it, and if you don’t, feel free to contact me via http://www.itknowledge24.com/contact.php.
 
The first two lines in this code, we tell NASM that we want it to assemble the output file for 16-bit, we set the boot origin to 0x7c00h which is the standard boot origin in which BIOS loads us at.

bits 16 ; 16-bit Real Mode
org 0x7c00 ; BIOS boot origin

 
In the next line we jump to the main() code-entry

jmp main ;Jump to start main() entry-point

In the next line we declare three text (strings) variables.

Message db "Hello World, booting from low-level 16-bit...", 0x0 
MessageB db "Fisnik's own bootloader program written in x86 assembly language.", 0x0
AnyKey db "Press any key to reboot...", 0x0

DB means declare byte.
 
Next, we make our own Println function with assembly code.

Println:
    lodsb
    or al, al
    jz complete
    mov ah, 0x0e 	
    int 0x10 ;BIOS Interrupt 0x10 - Used to print screen on Video Memory 
    jmp Println ;Loop   	
complete:
    call PrintNwL

 
The Println function, loads string bytes using lodsb, checks if AL==0 i.e. null, if null termination was found jz will jump to complete and call PrintNwL, but if AL!=0 i.e. does not equal null, make ah = 0x0E and invoke int 0x10, once character printed, keep looping until null termination. This is very straight forward to understand.
 
Next, we made our own Print New Line ‘\n’ function

PrintNwL: 
    mov al, 0	; null terminator
    stosb

    ;Adds a newline break '\n'
    mov ah, 0x0E
    mov al, 0x0D
    int 0x10
    mov al, 0x0A 
    int 0x10
	ret

 
The PrintNwL function, sets al=0, causing ‘\0’ null termination, next it stores the string bytes using stosb. The we set ah = 0x0E, in addition we set al = 0x0D and invoke the int 0x10 BIOS function.
 
Next we make the Reboot function which reboot the PC when called.

Reboot: 
    mov si, AnyKey ;Store the variable AnyKey in SI (Source Index)
    call Println
    call GetPressedKey 

    ;Sends us to the end of the memory
    ;causing reboot 
    db 0x0ea 
    dw 0x0000 
    dw 0xffff

 
The Reboot function, stores AnyKey into the SI, and calls Println. Next, GetPressedKey function is called, and the program waits for GetPressedKey to return, once returned we set db 0x0ea, and point us to 0xffff:0x0000h, the end of memory (RAM) causing PC reboot. I explained what DB is, but what is DW? DW means Declare word.
 
Next we make the GetPressedKey function which waits for the user to press any key on the keyboard and returns when called.

GetPressedKey:
    mov ah, 0
    int 0x16
	ret

 
That’s it, now we’re done with all of the functions, let’s analyze the first 6 lines in main.

   cli ;Clear Interrupt Flag to equal 0 (Disable)
   ;Setup stack segments 
   mov ax,cs              
   mov ds,ax   
   mov es,ax               
   mov ss,ax                
   sti ;Set Interrupt Flag to equal = 1 (Enabled)

 
First, we clear interrupt and disable, then we store data from code segment (CS) to AX (Accumulator), next we store data from AX to data segment (DS), next we store data from AX to extra segment (ES), and finally we store data from AX to stack segment (SS), and we re-enable the interrupts by setting the interrupt flag to equal = 1.
 
Finally the last two lines in this code.

 times 510 - ($-$$) db 0 ;Fill the rest of the bootloader with zeros 
 dw 0xAA55 ;Boot signature

 
We use the TIMES directive to insert exactly enough 0 bytes into the output to move the assembly point up to 510. The single dollar sign ($) refers to the address of the current line being assembled, and the double dollar sign ($$) refers to the address of the current section. The $-$$ returns the size of the program. The last line in our bootloader is dw 0xAA55 which is the magic number for the boot signature, BIOS INT 0x19 searches for bootable disk, and looks for the following 511 == AA, and 512 == 55, when this is confirmed INT 0x19 loads the program and executes the code.
 
To build this using NASM, open the Windows Command Prompt (CMD) and move to the directory where you’ve stored the NASM files, make sure boot.asm is stored in the exact same location and execute the following command:

nasm -f bin boot.asm -o boot.img

 
This will produce boot.img, now open VMware Workstation, and select one of your virtual machines, and click the Floppy icon and select Use Floppy Image file, and browse and select the boot image file produced by NASM. Next power the virtual machine.
 

My bootloader running in VMware.
 
If everything worked, congratulations! If something did not work, it is probably because there is a difference between your machine and mine. Or you might have had some issues with the assembly code, but this is easy to fix.
 
 

Error LNK1123: failure during conversion to COFF: file invalid or corrupt

Yesterday, I encountered an error in Microsoft Visual Studio 2010, when I in a discussion with a friend tried to run the C code example of “hello world” written in my first post on this blog. Visual Studio reported, Error LNK1123: failure during conversion to COFF: file invalid or corrupt. Hmm, what happened just?

 

 

 

Well, visiting Linker Tools Error LNK1123 at MSDN didn’t provide me with a direct solution to my problem. I went back to the project properties, and found out that in the General settings under the Linker settings, the Enable Incremental Linking was set to Yes (/INCREMENTAL).

 

Enable Incremental Linking simply means that the linker links your *.exe or *.DLL in a smarter way which makes it easier for the linker to update the existing *.exe or *.DLL when you make a small change in the code, and recompile it.

 

However, to fix this problem simply change the Enable Incremental Linking to No (/INCREMENTAL:NO) and click OK.

 

 

I hope this information solved your C/C++ linker issues in Microsoft Visual Studio.

 

Hello World – welcome to my Blog!

Hey, welcome! This is my computer and programming blog, it is finally up and running. I want to say “Hello World!” in a few languages, see them below.

 

C:

#include <stdio.h>
#include <windows.h>

int main(){
    printf("Hello World!\n");
    system("pause");
    return 0;  
}

C++:

#include <iostream>

using namespace std; 

int main(){ 
    cout << "Hello World!" << endl; 
    cin.get(); 
    return 0; 
}

C#:

using System;
using System.Collections.Generic;
using System.Text;

namespace Hello_World
{
    class HelloWorld
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!\n");
            Console.ReadKey(); 
        }
    }
}

Thanks for visiting! Now I’m officially blogging in a way that I am expected too, we’ll see how long it lasts.