I put in this code which does what it's supposed to do, but perhaps there is a better or more general approach? I'm converting a 4-digit base 10 number e.g. "11" to base 16 e.g. "17" (which gets written out on the display as 11 when called with 17 because the function takes bits as argument).
int hex1 = perhapsprime / 1000;
int hex2 = (perhapsprime - hex1*1000) / 100;
int hex3 = (perhapsprime - hex2*100 -hex1*1000) / 10;
int hex4 = perhapsprime - hex3*10 - hex2*100 - hex1*1000;
int test = 16*16*16*hex1+16*16*hex2+16*hex3+hex4;
The integer "test" will have the correct value after this code was run, but is there a more efficient way to do it?
Update
I settled for the following that appears to be able to convert any number of digits to BCD:
int tbcd(int v) {
int total = 0;
int resultbase = 1;
while(v > 0) {
total += resultbase * (v % 10);
resultbase *= 16;
v /= 10;
}
return total;
}