Cause I made such a hash of my first attempt, and in an effort to provide
PORTABLE code to solve the problem, I submit this solution to convert to
and from BCD values stored in longs. This should work just as well for
ints and (in theory) chars and, indeed, any integral type. If it doesn't,
suggest ways to improve it, even at a significant speed/code size penalty.
#include <math.h>
long bcd(long decimal)
{
int i;
long result = 0;
for(i = 0; decimal; ++i) {
result += (decimal % 10) * (int) pow(16,i);
decimal /= 10;
}
return(result);
}
long dec(long bcd)
{
long result = 0;
int i;
for(i = 0; bcd; ++i) {
result += (bcd % 16) * (int) pow(10,i);
bcd /= 16;
}
return(result);
}
/* Code tested on all of one machine, but C is portable in theory. */