Reputation: 664
I am working on a microcontroller which only outputs number in a hexadecimal representation. I have data which is calculated in decimal and is meant for a human to read and interpret. My output is the three decimal numbers 45, 27, and 91, when I output these I get 0x2D, 0x1B, and 0x5B. What operation can I perform to convert 45 to 0x45, 27 to 0x27 and so on.
Upvotes: 1
Views: 1271
Reputation: 71
Though I think it is not a good idea to convert 45 to 0x45, here is the method:
int dec = 45;
int hex = 0;
int i = 1;
while(dec/10 != 0){
int digit = dec%10;
hex += digit*i;
i *=16;
}
cout << hex << endl;// if you convert "hex" to hexadecimal, it would be 0x45
Upvotes: 1
Reputation: 2138
If I understand you correctly you want something like this:
unsigned char convert(unsigned char in) {
return ((in % 10) * 0x01) + ((in / 10) * 0x10);
}
int main()
{
unsigned char a = 45;
printf ("0x%02X", convert(a)); // prints "0x45"
return 0;
}
It converts the decimal value 45
to 0x45
which is equivalent to decimal 69
.
Note that the convert function is not really fast on microcontrollers because of the division /
.
It can only print decimal values from 0 to 99 because there are only two digits to use.
Upvotes: 2