Monday, February 8, 2010

OOP344 - fardad, i accept your putint() challenge!

this function was harder than i expected. In order to convert a number to a character, all you have to do is add 48 (this is because 0 on the ascii table is 48, 1 is 49, etc.). So as long as you are sending the putint function a 1 digit number, this will work. However, for the keys that are 4 digits long (i.e: RIGHT_KEY = 1077), it gets a little more complicated.

This took me a while to figure out and i must say, it's genius :). First what you have to do is: seperate the digits. This is where being good with numbers really helps.
(i'm not going to write code, instead I'll give you a mathematical view point)

if you divide a number by 10, the decimal moves one point to the left:
1077 / 10 = 107.7
In order to get the decimal point i used a float, however that caused problems because float are never exact. So, i made two temporary int variables and did this:

1. temp = 1077 <- this is the integer being sent to the function
temp / 10 = 107 <- integers truncate decimal points
temp * 10 = 1070
2. temp2 = 1077 - temp
= 7
Hooray, i got the first digit separated. Now, just do char = temp2 + 48; and your first digit is successfully converted. Repeat this process for x amount of times and your string contains a 4 digit number. BUT WAIT, how do i determine x? dividing by 10 again.
make a while loop where you divide temp by 10 while temp > 0 and do an i++ to get how many digits are in the number. you can now use i for a for loop.

There you have it, a putint function that converts an integer into a string without using extra libraries (there is no atoi() or sprintf()).