Lots of reasons!
1) Because you are extracting digits in the wrong order.
If I enter "1a3" then your loop will first extract the "3", then the "a", then the "1".
You need to work from the most significant digit first not the least, or reverse the output before you print it.
Hint: If you work from the end of
binary
instead of the front it might work better.
2) Because the "%" operator returns an integer, not a character.
3 in an integer is not the same as '3' the character value, and when you cast an integer to a char value, it doesn't change it: it leave it as the value 3 in a char variable. That isn't the same as '3' which has a value of 0x33:
ASCII - Wikipedia[
^]
3 the value in a char is what is called a "control code" called "ETX", and it=s used to "Frame" data.
Hint: Remove the quotes from your cases and try again:
case 0:
strcat(binary,"0000");
break;
case 1:
strcat(binary,"0001");
break;
...
You will need to do something about 'a' to 'f', but I'll leave that to you.
Suggestion: Always add a
default
to a
switch
so do something sensible when you get a value you haven't allowed for: print it with an error message, for r example.
3) Because
x % 10
doesn't give you a hexadecimal digit: it gives you a decimal digit. Likewise,
x / 10
doesn't discard a hex digit but a decimal one.
Hint: try using 16 instead of 10, or extract a hex digit by ANDing it 0x0f.
4) Because
scanf("%d", ...)
doesn't read a hexadecimal number:
scanf format string - Wikipedia[
^]
Hint: There is no format code for "read a hex number": either read a decimal number and convert that to binary, or read a string and validate it before converting to a numeric value.
To be honest, you should have spotted most of these pretty quickly for yourself: if you had used the debugger to see what was happening, you would have had an easier time.
I would strongly suggest that you learn how to use the debugger on your system - it can let you look at and control your code while it is running, including examining and changing the value of variables. It's the most powerful tool you have, and you will probably spend more time there testing and fixing your code than you will writing it!
If you don't know how to use a debugger, then Google will help - search for the name of your IDE and "Debugger" and you will find loads of information!