Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an Unsigned Character array into a hexadecimal string in C

Tags:

c

string

types

Is it possible to represent an unsigned character array as a string?

When I searched for it, I found out that only memset() was able to do this (But character by character). Assuming that is not the correct way, is there a way to do the conversion?

Context: I am trying to store the output of a cryptographic hash function which happens to be an array of unsigned characters.
eg:

unsigned char data[N]; ...
for(i=0;i<N;i++) printf("%x",data[i]);

My goal is to represent the data as a String (%s) rather than access it by each element. Since I need the output of the hash as a String for further processing.

Thanks!

like image 314
Maverickgugu Avatar asked Apr 14 '11 09:04

Maverickgugu


3 Answers

So, based on your update, are you talking about trying to convert a unsigned char buffer into a hexadecimal interpretation, something like this:

#define bufferSize 10
int main() {
  unsigned char buffer[bufferSize]={1,2,3,4,5,6,7,8,9,10};
  char converted[bufferSize*2 + 1];
  int i;

  for(i=0;i<bufferSize;i++) {
    sprintf(&converted[i*2], "%02X", buffer[i]);

    /* equivalent using snprintf, notice len field keeps reducing
       with each pass, to prevent overruns

    snprintf(&converted[i*2], sizeof(converted)-(i*2),"%02X", buffer[i]);
    */

  }
  printf("%s\n", converted);

  return 0;
}

Which outputs:

0102030405060708090A
like image 149
forsvarir Avatar answered Jan 04 '23 13:01

forsvarir


In C, a string is an array of char, terminated with a character whose value is 0.

Whether or not char is a signed or unsigned type is not specified by the language, you have to be explicit and use unsigned char or signed char if you really care.

It's not clear what you mean by "representing" an unsigned character array as string. It's easy enough to cast away the sign, if you want to do something like:

const unsigned char abc[] = { 65, 66,67, 0 }; // ASCII values for 'A', 'B', 'C'.

printf("The English alphabet starts out with '%s'\n", (const char *) abc);

This will work, to printf() there isn't much difference, it will see a pointer to an array of characters and interpret them as a string.

Of course, if you're on a system that doesn't use ASCII, there might creep in cases where doing this won't work. Again, your question isn't very clear.

like image 27
unwind Avatar answered Jan 04 '23 12:01

unwind


Well a string in C is nothing else than a few chars one after another. If they are unsigned or signed is not much of a problem, you can easily cast them.

So to get a string out of a unsigned char array all you have to do is to make sure that the last byte is a terminating byte '\0' and then cast this array to char * (or copy it into a array of char)

like image 34
Chris Avatar answered Jan 04 '23 13:01

Chris