Page 1 of 1

printing integers/numbers

Posted: Wed Apr 23, 2003 6:44 pm
by slacker
i have been searcing all over the internet but havent found any documentation on printing numbers. does anyone know a site...?

Re:printing integers/numbers

Posted: Wed Apr 23, 2003 9:26 pm
by Dav
I haven't found a site about it. However I might be able to help you.

This is mainly for single digit numbers but it can be extented to multi-digit numbers even floats.

Firstly you must convert the integer to its ASCII equivilant.

Converting the number to an ASCII code:
It can be seen from looking at an ASCII chart that the ASCII code of 0 is 0x30, 1 is 0x31, 2 is 0x32 and so on. So it's a simple matter of ORing the number with 0x30 to get to the ASCII Code.

Then print it as you would a single character.

I hope this helps.

[edit] Added some sample code:

char NumberToString(int num)
{
   char c;
   c = num | 0x30;
   return c;
}

Re:printing integers/numbers

Posted: Wed Apr 23, 2003 9:32 pm
by _mark
Something simple from my bootloader:

void __far format_short( unsigned short num, char __far *buf )
{
   int         i;

   buf[0]= (num&0xF000)>>12;
   buf[1]= (num&0x0F00)>>8;
   buf[2]= (num&0x00F0)>>4;
   buf[3]= (num&0x000F);

   for ( i=0; i < 4; i++ )
   {
      buf= (buf<10) ? '0' + buf : 'A' + buf - 10;
   }
}

This formats a short into HEX. HEX is easy to print, because each nibble is just a digit. It is also nicer for printing address and such. Base 10 is just about as easy. Basically just keep mod (%) the number by 10 to get the remainder. The remainder will get added to '0' to give you a digit. Then devide by 10. Do this until your number is zero. This will usually yeild a backwards number so you then need to reverse the buffer.

_mark()

Re:printing integers/numbers

Posted: Thu Apr 24, 2003 1:42 am
by Pype.Clicker
my favourite print_hex code :

Code: Select all

print_hex(int val, char *buffer)
{
     static char digits[]="0123456789abcdef";
     char *p=buffer+8;
   
     for(;p!=buffer;p--,val=val>>4) 
        *p=digits[val&0x0f];
}
btw, consider putting your code between [ code ] and [ / code ] if you don't want array indices [ 0 ] to become list decorators like [0].

Re:printing integers/numbers

Posted: Thu Apr 24, 2003 1:00 pm
by slacker
k now that i know that there is no way to directly print the integers without changing them to ascii (which i should of already known) im going to set up an array like one similar that is used in my keyboard driver...