converting hex to binary
Hello, I have to design a program which takes 4 integer values from the user as well as a 2 digit hex value. The program then performs some arithmetic based upon that hex value's binary equivalent. I know how to write most of the program, however, I am not sure how to convert my hex value into binary. I read it in using %x and store that value in an unsigned int. How do I take this value and convert it to binary or does storing it as an unsigned int already handle that ?
Welcome to the forum, Brian! :cool:
Since it's the middle of the night and I'm FRIED, I'll let someone with more active brain cells respond. You might want to read up on "two's compliment", in the meantime.
It depends on what you mean by "convert the hex value into binary".
Format specifiers (%d, %x) change how the data is read from a file (or keyboard). They don't change how an unsigned int represents a value. So
then, if you input "175 AF", x and y will both receive the same value (175). The difference is in how input data is processed to extract the value. The unsigned type supported by your compiler will represent the value 175 in the same manner, regardless of whether it was read as 175 (using the %u format) or as AF (using the %x format).
scanf("%u %x", &x, &y);
If you want to print the binary digits, then you need to compute the value of each digit before outputting it. The usual technique involves determining if the value is odd, and dividing by 2, repeatedly until all binary digits are printed.
But you don't need to do anything to the value read if you use the correct format specifier. That is the purpose of format specifiers .... to map between a value and output (or input) you need.
well I don't want to print the binary, rather once I have all 8 binary digits, I want to manipulate them bit shift operators. This part I know how to do. you're saying the best way to get the 2 digit Hex into binary is with that division method, correct ?
No. Read my post again. I said your question could have more than one meaning.
If you want to get input into a variable, use a format specifier. Then use bit shift operators on the variable. That's it.
The only exception is if you want to print each binary digit (i.e. print a string of 0's and 1's) - which you've now just said is not what you want to do.
that makes perfect sense now. thanks!