Convert unsigned char array to hex string

#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



typedef unsigned char octet_t;

#define MAX_PRINT_STRING_LEN 1024;

char bit_string[MAX_PRINT_STRING_LEN];

octet_t nibble_to_hex_char(octet_t nibble) {
  char buf[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
		  '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  return buf[nibble & 0xF];
}

char *
octet_string_hex_string(const void *s, int length) {
  const octet_t *str = s;
  int i;
  
  /* double length, since one octet takes two hex characters */
  length *= 2;

  /* truncate string if it would be too long */
  if (length > MAX_PRINT_STRING_LEN)
    length = MAX_PRINT_STRING_LEN-1;
  
  for (i=0; i < length; i+=2) {
    bit_string[i]   = nibble_to_hex_char(*str >> 4);
    bit_string[i+1] = nibble_to_hex_char(*str++ & 0xF);
  }
  bit_string[i] = 0; /* null terminate string */
  return bit_string;
}

你可能感兴趣的:(convert)