weirdVariable
weirdVariable

Reputation: 97

Using hex characters as input to a c program changes the characters?

I have a short c program called "hex" that takes two characters and outputs their corresponding hex code:

int main(void) {
    unsigned char var[3];
    printf("Enter two hex characters: ");
    scanf("%2s", var);
    printf("%x ", var[0]);
    printf("%x ", var[1]);

}

Now when I call this program with an input consisting of the two characters "A" and "0" in hex code:

echo -e "\x41\x00" | ./hex

Then the output is (as expected) "41 0". But when I call this program two times with the hex code "0d":

echo -e "\x0d\x0d" ./hex

Then the output is "0 bb" ? Why is it like that? What can I do to use the correct input for the hex code "0d"s instead of what I'm using?

EDIT: The scanf should be before the print statements, that was a copy paste error. I corrected it.

Upvotes: 0

Views: 97

Answers (2)

0___________
0___________

Reputation: 67476

your code is one big Undefined Behaviour. You print elements of the uninitialised array. After printing you scanf those elements.

Don't you think that the order is a bit weird?

Upvotes: 0

MikeCAT
MikeCAT

Reputation: 75062

The printings must be after reading.

Also %s will skip newline characters and \x0d is CR, which is one of newline characters, so you should use fread() to avoid the input being skipped.

#include <stdio.h>

int main(void) {
    unsigned char var[3];
    fread(var, 1, 2, stdin);
    printf("%x ", var[0]);
    printf("%x ", var[1]);
    printf("Enter two hex characters: ");
}

Upvotes: 1

Related Questions