arraysccastingtype-conversionunsigned-char

How to convert elements in const unsigned char array to char


I am trying to iterate over a single const unsigned char array and assign/convert each element to a new char array using typecasting, every thread I've read suggests using typecasting however it's not working for me, here's my attempt:

#include <stdio.h>
#include <stdlib.h>

char *create_phone_number(const unsigned char nums[10]) {
  char *new = malloc(11);
  int i = 0;
  for (; i<10; i++) 
    new[i] = (char)nums[i];
  new[i] = '\0';
  return new;
}

int main(void) {
    char *num = create_phone_number((const unsigned char[]){ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 });
    printf("%s\n", num);
    free(num);
    return 0;

}

The above code's stdout:

Expected stdout:

1111111111

How do I convert the elements in nums to type char and assign/store the converted values in the new array (efficiently)?


Solution

  • Casting to char doesn't mean casting the integer value to the corresponding ASCII character; the numeric value 1 is the ASCII code SOH (start of heading) which has no printable representation, thus your empty output. If you know all the values will be in the range 0 to 9, you can add them to ASCII '0' to get the char value that produces the associated ASCII digit:

    char *create_phone_number(const unsigned char nums[10]) {
      char *new = malloc(11);
      for (int i=0; i<10; i++) 
        new[i] = '0' + nums[i];
      new[i] = '\0';
      return new;
    }
    

    You don't actually need to cast it at all; the result of the + will be int and it will store back to a char that can fit it without issue (so just make sure they're really all 0-9 values, or you'll get weird results).