Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C string and hex characters

Tags:

c

c-strings

Can anyone explain what is happening in this code?

    #include <stdio.h>

    void f(const char * str) {
      printf("%d\n", str[4]);
    }

    int main() {
      f("\x03""www""\x01""a""\x02""pl");
      f("\x03www\x01a\x02pl");
      return 0;
    }

why output is?

    1
    26
like image 531
Pikacz Avatar asked Aug 28 '15 17:08

Pikacz


People also ask

What is\ x01 in c?

In C, characters specified in hex (like "\x01" ) can have more than two digits. In the first case, "\x01""a" is character 1, followed by 'a'. In the second case, "\x01a" , that's character 0x1a, which is 26. Follow this answer to receive notifications.

What is hex and ascii?

There is no difference between "ascii" and "hex". It's simply a matter of you displaying it how you want to. All ascii characters have a decimal value. Oddly enough, decimal can be converted (read: displayed in) to hex. It's up to you do pick what way you want to display whatever it is you're displaying.


2 Answers

The issue is with "\x01""a" versus "\x01a", and the fact that the hex->char conversion and the string concatenation occur during different phases of lexical processing.

In the first case, the hexadecimal character is scanned and converted prior to concatenating the strings, so the first character is seen as \x01. Then the "a" is concatenated, but the hex->char conversion has already been performed, and it's not re-scanned after the concatenation, so you get two letters \x01 and a.

In the second case, the scanner sees \x01a as a single character, with ASCII code 26.

like image 150
Jim Lewis Avatar answered Nov 06 '22 13:11

Jim Lewis


In C, characters specified in hex (like "\x01") can have more than two digits. In the first case, "\x01""a" is character 1, followed by 'a'. In the second case, "\x01a", that's character 0x1a, which is 26.

like image 21
Lee Daniel Crocker Avatar answered Nov 06 '22 11:11

Lee Daniel Crocker