Saturday, 15 September 2012

Program : HEX To ASCII Conversion

::::: HEX to ASCII Conversion in C :::::
 
Hello Everyone,

If you're willing to convert the values of 0 to 999 Decimal range (8 bit data) into their ASCII values then here is the program with explanation :


(and if you have 16 bit data then I'll post that too, just tell me)


void main()
{
    unsigned char x,y,d1,d2,d3;
    y = 0xFD;                  // y is your value, here I've take 0xFD  (253 in Decimal)
    x = y / 10;                // after execution, x will have answer and y will have remainder
                                         //(x=25 & y=3)
   d1 = y % 10             // after execution y will have no change and d1 will have
                                         //remainder (y=3 & d1=3)
                                   // means you've got d1;your LSD (Least Significant Digit)
   d2 = x % 10             // after execution x will have no change and d2 will have
                                        //remainder (x=25 & d2=5)
                                  // means you've got d2;your middle Digit
   d3 = x / 10;             // after execution d3 will have answer and x will have remainder
                                       //(d3=2 & x=5)
                                // means you've got d3;your MSD (Most Significant Digit)

// now we need to display all three digits 'd3=2' , 'd2=5' & 'd1=3'.
// (Here you'll never get d1,d2,d3 greater than 9. If you get then there must be a mistake //anywhere in program.)
// Now to convert them into the ASCII you need to add 30H in these values

   d1+=0x30;
   d2+=0x30;
   d3+=0x30;

// Now you have 'd3=0x32' , 'd2=0x35' & 'd1=0x33'

// And these new values are the ASCII Code of your actual numbers
(Remember : by adding 30H  you get ASCII)

// Now just send these variables to LCD and display them

// Hope this helps you

}


Normally to get no.s displayed people often uses "sprintf" function in C, but it occupies a large space in your memory.
So this one is the better option to do so.
Thanks

No comments:

Post a Comment