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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With