2

How to convert variable unsigned char with HEX value to variable int with DEC value. I have got:

unsigned char length_hex = 0x30; // HEX

How to convert to int DEC?

int length_dec = length_hex; // With result length_dec = 48
Tommy Andersen
  • 7,165
  • 1
  • 31
  • 50
Ruslan Skaldin
  • 981
  • 16
  • 29
  • Possible duplicate of [Why are hexadecimal numbers prefixed with 0x?](http://stackoverflow.com/questions/2670639/why-are-hexadecimal-numbers-prefixed-with-0x) – Nikita Nov 09 '16 at 11:17
  • 1
    Hexadecimal and decimal are only how you view the numbers. It's all stored in binary anyway. And no you don't need any conversion, it's all "automatic". Just try to print out `length_hex` as an `unsigned int` and see the result (e.g. `std::cout << static_cast(length_hex)`) – Some programmer dude Nov 09 '16 at 11:17
  • 1
    So you basically answered your own question in the last line? :) – Tommy Andersen Nov 09 '16 at 11:20
  • I didn't got you question. `0x30` simply means 48 so `unsigned char length_hex = 0x30;` and `unsigned char length_hex = 48` are the same thing – Elvis Dukaj Nov 09 '16 at 11:23
  • I got it, in a cycle it works the same with len = 0x30 or len = 48. – Ruslan Skaldin Nov 09 '16 at 11:33

1 Answers1

0

As some people have commented the conversion is automatic. Try:

int main (void)
{
    unsigned char length_hex = 0x30;
    printf("0x30 is char:%c and int:%d.",length_hex,length_hex);
    return 0;
}

and see what you get - when you convert it to a char it's '0' (the character 0) and as an int it's 48. Also, it doesn't really matter if I save the constant 0x30 as an int or char. Just look at:

printf("0x30 is char:%c and int:%d.",0x30,0x30);
kabanus
  • 24,623
  • 6
  • 41
  • 74
  • `0x30` in ASCII code is exactly char `'0'` I cannot got the point! So I expect `0x30 is char 0 and int is 48` – Elvis Dukaj Nov 09 '16 at 11:27
  • Correct, what's your question? I'm just showing the conversion is automatic to int and char respectively. – kabanus Nov 09 '16 at 11:28