Page 380 - Programming Microcontrollers in C
P. 380
Coding the Alpha Data 365
while(*ptr!=’\0')
{
if(*ptr++==’1')
array[i]|=bit;
bit>>=1;
if(bit==0)
{
bit=bitbase;
i++;
}
}
}
}
return ++i; /* the length of the coded array */
}
Listing 7-6: Encode Function
The program then enters a while loop that examines the contents
of the code received. If the leftmost entry is a character ‘1’ a value of
bit is ORed into the location array[i]. In either case,
*ptr==’1’ or *ptr==’0’, the value of bit is replaced by bit
shifted right by 1. Whenever bit has been shifted until its value
becomes zero, it indicates that the unsigned int value pointed to
by ptr has been filled and bit is reinitialized to bitbase. Also at
this time i, the index into array[], is incremented to get the next
character to decode.
Decoding the alpha data
The above function encodes the alpha data entered in the array
s[] into a Huffman code of the same data and returns the encoded
data in the array array[]. Perhaps the easiest way to test the
encode routine is to execute it in conjunction with its corresponding
decode routine. The decode operation essentially recreates the tree
shown in Figure 7-1. Rather than a two-dimensional rendition, it
must be a single-dimension list. The list will have built-in mechanisms
for traversing the tree from its root node to the encoded character
based on the 1 and 0 patterns in the encoded data.