Thread: Reverse conversion

1. Reverse conversion

Is it possilbe to reverse this piece of code to do the opposite? Right now it succesfully converts a hexadecimal number to a binary. How can I make it do the opposite? thanks.

Code:
```int funcHexBin()/*function that converts hex to binary*/
{

char hex[] = "0123456789ABCDEF";
char *bin[] = { "0000", "0001", "0010", "0011", "0100", "0101",
"0110", "0111", "1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111" };

printf("Enter a Hexadecimal(use capital letters only): \n");
scanf("%s", &userhex2);

strl = strlen(&userhex2); /*get the length of the string*/

char *userhexd = &userhex2;
for (strl;strl>0;strl--)
{
printf("%s", bin[strchr(hex, *userhexd)-hex]);
userhexd++;
}
putchar('\n');

system("PAUSE");
return 0;
}```

2. Easy if you want to print an integer in hexadecimal you don't need to use any function just use printf with the %x flag as follows.

Code:
`printf("%x\n", int);`
If you want to convert it from binary to hex then just read each succesive 4 bits and convert it into its equivalent hex number.

3. Originally Posted by stumpster123
Easy if you want to print an integer in hexadecimal you don't need to use any function just use printf with the %x flag as follows.

Code:
`printf("%x\n", int);`
If you want to convert it from binary to hex then just read each succesive 4 bits and convert it into its equivalent hex number.
Ok that makes sense. however when a user entered a string such as 1001001011000011 how can i go about splitting it every 4 digits?

4. Well, to convert a string that holds 4 bits you could do something like this:
Code:
```char string[] = "1001";
int num4bits;

num4bits = string[3] - '0';
num4bits |= (string[2] - '0') << 1;
num4bits |= (string[1] - '0') << 2;
num4bits |= (string[0] - '0') << 3;

// Now print num4bits with printf() using the %x format specifier```
Put that in a loop to keep grabbing 4-character segments of the string until you run out of characters in the string to grab.

5. ahh thanks, that works

Popular pages Recent additions