Page 367 - Programming Microcontrollers in C
P. 367
352 Chapter 7 Advanced Topics
Numeric Encoding
Data will be entered from a keyboard that is assumed to provide
an ASCII character stream. In operation, the first entry will be the
telephone number. As this number is received the coding will be
converted from ASCII to a modified BCD format. The modification
is needed to eliminate trouble with the occurrence of zeros in the
number. The conventional BCD encoding for a zero is a 0x0 that is 4
bits wide. If you should have a double zero, the encoded version
would be an 8-bit zero or ‘\0’, which is interpreted in C as an end of
a character string. That confuses the issue enough that it was decided
to encode the digit zero as 0xa. The literal interpretation of this
number is the value ten. But, with our BCD encoding, the number
ten will never occur, so it is safe to use this value for the value zero.
/* The ascii data in the constant array s[] con
tains a number. These data are converted to a
modified BCD form and stored in the array
array[]. The number zero is stored as 0xa. The
series is terminated with a null character
followed by an enter character. */
#include <ctype>
int numbdup(char * const s, unsigned *array, int len)
{
char *pq,*sp;
int i;
sp=s; /* use local pointer */
pq=(char *)array; /* convert pointer to character */
for(i=0;i<len;i++) /* empty the array */
pq[i]=0;
i=0;
while(*sp!=’\0'&&*sp!=’\n’) /* read until termination char*/
{
*pq=0;
if(isdigit(*sp))/*converttheinputstwoat atime*/