1

Im trying to convert an escaped hexadecimal value to an integer. How should i do this.

I've tried it with strtol but this only produces the correct number if the hex is not escaped.

int number = (int)strtol("0x10", NULL, 16); //16
int number = (int)strtol("\x10", NULL, 16); //0
toaster_fan
  • 185
  • 1
  • 13
  • If you escape then the compiler will do the translation by itself, and then the *string* does not represent a correct hex value. – Jean-Baptiste Yunès Apr 08 '20 at 15:26
  • If you do this: `int n = "\x10"[0]; printf("%d\n", n);` you'll see that the escaped hex value is encoded *as is* into the character. – Adrian Mole Apr 08 '20 at 15:31
  • 1
    `"\x10"` is a string with a two characters, one with a value of `16` and other being the NUL-terminator. `"0x10"` is a proper NUL-terminated string representation of a hexadecimal number and what strtol expects to be passed as a argument. For your first case, to get the hexadecimal number, you need to do `(int)(*"\x10")` instead. – Ruks Apr 08 '20 at 15:31

1 Answers1

0

"0x10" means the C-string containing 4 characters (plus the ending NUL byte), '0', followed by 'x', followed by '1', followed by '0'.

"\x10" means the C-string containing 1 character (plus the ending NUL bytes), the sixteenth character of the ASCII table. The compiler interpret the content of your string by doing the conversion by itself, thus replacing the full sequence \0x10 by its value. Then strtol is unable to understand this as a representation of an hex number representation, and then returns 0 :

strtolmanual : If no valid conversion could be performed, a zero value is returned (0L).

Read What does \x mean in c/c++?.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69