CODE- TALES: Series I


In this first series of CODE-TALES, let me take this opportunity to congratulate my friend Dhananjay Kumar on being awarded Telerik MVP (another feather in your cap). He has been a big inspiration for many; we both started our journey from the same place and I still remember when you joined us in MS COE team as a young professional who chose his path to success indifferent to what others thought or said about him. Keep moving forward...

About


CODE-TALES is an effort for passionate technologists who are always out there trying to learn every day, I can assure you that each series will bring a new topic and though there can be several ways to do the same thing, so any approach other than penned down here is always welcomed.

Simple Mathematics Operator

Yes you guessed it right, today we will discuss and see how simple mathematics can be implemented in the world of computers; this question always intrigued me.

Problem

Given the two numbers a and b, I want to add the two numbers (a + b) to get its sum.

Solution

Now we are actually trying to implement the '+' operator, giving our own meaning to the operator. Usually there would be somewhere some compiler of a particular language or Operating System API that would givie us the definition of the + operator and that means somewhere someone would have given (written) that definition, so the question still remains how ?? Well that is what we will discuss in this series.

We will be using the bit operators and logical operators in Digital Electronics to implement our addition operation. So a brief understanding of the same is required (discussion of which is out of scope of this series).

Let us see the pseudo code for the same first:

Repeat:

add = a XOR b
carry = ( a AND b ) << 1
a = add
b = carry
while carry is not zero
return add.

Now let us see how this algorithm works with a help of an example:

Let a = 2, b = 3

Loop I

In the binary world a variable a can be represented as: 0010 and b as: 0011

0010 0010
0011 0011
------- ------
0001 (add) 0010 << 1 = 0100 (carry)

Loop II

Since the carry is not 0, we continue:

0001 0001
0100 0100
------ ------
0101 (add) 0000 << 1 = 0000 (Finish point)

Since here the carry becomes zero so our algorithm stops here and we see the final value of variable add is: 0101 which is decimal equivalent of 5.

Problem

Given two numbers a and b, I want to subtract two numbers (a - b) to get its difference.

Solution

Well we can look at this problem as: a + (-b) or in other words a + (~b + 1)

And we can thus represent subtraction in terms of an addition method which we defined above a short while ago.

Well, this is all we have for this series, in the coming series we will see how we can do the same for multiplication as well as division operation. The code sample for the same is available in C# / C++ / Java language.

 


Similar Articles