void setup() {
int val = 0xE5;
char buffer[20];
Serial.begin(115200);
decimalToHex(val, buffer);
Serial.print("decimal "); Serial.print(val); Serial.print(" in hex is: "); Serial.println(buffer);
Serial.print("ascii: "); Serial.println((char)val);
Serial.print("strtol: "); Serial.println(strtol(buffer, 0, 16));
Serial.print("First hex digit value: ");
Serial.println(hexToDecimal(buffer[0]));
Serial.print("Second hex digit value: ");
Serial.println(hexToDecimal(buffer[1]));
}
void loop() {
}
/*****
Function that converts decimal value to a hex string
Argument list:
int n; the decimal value to convert
char hex[] the buffer to hold the conversion
Return value:
void
Caution: This function assumes the buffer is large enough to hold
the output.
*****/
void decimalToHex(int n, char hex[])
{
int i = 0, rem;
while (n > 0)
{
rem = n % 16;
switch (rem)
{
case 10:
hex[i] = 'A';
break;
case 11:
hex[i] = 'B';
break;
case 12:
hex[i] = 'C';
break;
case 13:
hex[i] = 'D';
break;
case 14:
hex[i] = 'E';
break;
case 15:
hex[i] = 'F';
break;
default:
hex[i] = rem + '0';
break;
}
++i;
n /= 16;
}
hex[i] = '\0';
strrev(hex); /* Reverse string */
}
/*****
Function that converts hex digit to a decimal value
Argument list:
char hex the hex digit to convert
Return value:
int
*****/
int hexToDecimal(char hex) /* Function to convert hexadecimal to decimal. */
{
hex = toupper(hex);
int temp = hex - '0';
if (temp < 10)
return temp;
else
return hex - 'A' + 10;
}