View previous topic :: View next topic |
Author |
Message |
saholt
Joined: 07 Oct 2003 Posts: 3 Location: North Wales. UK
|
Decimal number to individual chars |
Posted: Tue Jan 27, 2004 6:21 pm |
|
|
Help, does anyone know how to take a decimal value eg. 1234 and convert this to 4 individual characters eg 1 2 3 4. Any help greatfully appreciated. |
|
|
dyeatman
Joined: 06 Sep 2003 Posts: 1933 Location: Norman, OK
|
Convert 1234 |
Posted: Tue Jan 27, 2004 6:38 pm |
|
|
The easy way is to use the sprintf() function
dave
Last edited by dyeatman on Tue Jan 27, 2004 6:40 pm; edited 1 time in total |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Tue Jan 27, 2004 6:38 pm |
|
|
Use the sprintf() function to convert a 16-bit integer to an ASCII string.
After executing the following program, the contents of the buffer[]
array will be:
buffer[0] = '1'
buffer[1] = '2'
buffer[2] = '3'
buffer[3] = '4'
buffer[4] = 0
The use of single quotes around a number means it's an ASCII value.
The final 0 in buffer location 4, is the string terminator. It is not ASCII.
main()
{
char buffer[6]; // Allow enough room for 5 digits, plus the string terminator.
int16 value;
value = 1234;
sprintf(buffer, "%lu", value);
while(1);
} |
|
|
rrb011270
Joined: 07 Sep 2003 Posts: 51
|
|
Posted: Tue Jan 27, 2004 7:06 pm |
|
|
Mabuhay!
I hope this code snippet is of great help to you. This is based on the ASCII table of characters with their equivalent hex value.
Code: |
//************************************************************************
// convert ascii number string to integer number
unsigned int8 asciiNum2Int(unsigned int8 index)
{
unsigned int8 n;
n = rxbuffer[index];
if ((n<='9')&&(n>='0'))
return (n&0x0F); // Pure number 0 to 9
if ((n<='F')&&(n>='A'))
return ((n&0x0F)+9); // Hex nnumber A to F
if ((n<='f')&&(n>='a'))
return ((n&0x0F)+9); // Hex in lower case
return (0);
}
//************************************************************************
unsigned int8 ascii2int8(unsigned int8 indx) // convert ascii to interger
{
unsigned int8 cnvt=0;
//unsigned int8 indx=6; // start index for command code
cnvt = (asciiNum2Int(indx)*10) + asciiNum2Int(indx+1);
return(cnvt);
}
//************************************************************************
// convert ascii hex to long integer
unsigned int16 asciiHex2int16(unsigned int8 indx)
{
unsigned int16 addr=0; // address in word 0000 - FFFF
//unsigned int8 indx=2; // start index for MAC address retreival
addr = ((asciiNum2Int(indx))*4096) + ((asciiNum2Int(indx+1))*256) +
(asciiNum2Int(indx+2)*16) + asciiNum2Int(indx+3);
return(addr);
}
//************************************************************************
|
enjoy and share your snippet.... |
|
|
|