# Thread: Converting a binary string to hex

1. ## Converting a binary string to hex

I have a string in binary and I need to convert it to hex. (Obvious right?)

What I'm trying to do is this:
Code:
```for (z = 0; z < 20; z++)
sprintf(string, "%02x", out[z]);```
Both out and string are defined as unsigned char[20]

Now, I know that hex characters take two bytes, so I also tried
Code:
```for (z = 0; z < 20; z++)
y += sprintf(string+y, "%02x", out[z]);```
Where y is initialized to 0. I keep getting damage after normal block errors. I thought it was becuase I was overwriting memory so I increased the size of string to 200, which should be MORE than enough room, but I get the same error. Any suggestions?

2. You need to look at 4 binary digits to make 1 hex digit. Try:
Code:
```itsme@itsme:~/C\$ cat bintohex.c
#include <stdio.h>
#include <string.h>

int main(void)
{
unsigned char binstr[] = "1001110001100111";
unsigned char hexstr[5];
unsigned int hexnum;
unsigned char four[4];
int i, j;

for(i = 0;i < 4;++i)
{
hexnum = 0;

strncpy(four, binstr + (i * 4), 4);
for(j = 0;j < 4;++j)
hexnum += (four[j] - '0') << (3 - j);

sprintf(hexstr + i, "%X", hexnum);
}

puts(hexstr);

return 0;
}```
Code:
```itsme@itsme:~/C\$ ./bintohex
9C67
itsme@itsme:~/C\$```

3. There is a "secret" standard library function called strtol() [String To Long]. It can convert a string representation in (almost) any base to a type long.

Once you have a "regular" integer value, you can display it in decimal, octal, or hex with cout, or you can use sprintf() if you want a string representation.

code fragment...
Code:
```   int Base, x;
char InputString[40];
char *pEnd = NULL;          // Required for strtol()

cout << "Base? (2-36, 0 to exit) " ;
cin >> Base;

if(!Base)
return 0;

cout << "Number? ";
cin >> InputString;
x = (int)strtol(InputString, &pEnd, Base);     // String to long

cout << "\t" << dec << x << "\t\t Decimal" << endl;
cout << "\t" << oct << x <<  "\t\t Octal" << endl;
cout << "\t" << hex << x << "\t\t Hex" << endl;```

4. If I wanted to print x to a string using sprintf, what flag would I use within the sprintf? %x?

5. It occurs to me that I was unclear, what I'm trying to convert is not a string of ASCII characters representing binary, it's pure, raw binary data (Specifically from a SHA-1 message digest).

6. So you basically have an array of 20 unsigned 1-byte numbers? Are you just wanting to convert those 20 numbers into a string that represents them in hex?

Try changing the code you had:
Code:
```for (z = 0; z < 20; z++)
y += sprintf(string+y, "%02x", out[z]);```
to...
Code:
```for (z = 0; z < 20; z++)
sprintf(string+(z*2), "%02x", out[z]);```
You were close, but y is not needed. Your string only needs to be exactly 41 chars big to fit the hex string (2 chars for each of the 20 numbers plus 1 for the terminating zero).

7. Thanks much itsme86, that worked.