Home > Mobile >  Unsigned Short Array to Char Array
Unsigned Short Array to Char Array

Time:10-14

I've seen a little bit of code that deals with unsigned short arrays and storing "strings" in them. But I am curious how one might go about converting or extracting the string out of the unsigned short array into a char array for use in printf() for debugging purposes.

unsigned short a[5];
char b[5];

a[0] = 'h';
a[1] = 'e';
a[2] = 'l';
a[3] = 'l';
a[4] = 'o';

printf("%s\n", a);
// output is just the 'h'

From my recent understanding, an unsigned short is 2 bytes so the 'h' has a Null terminator with it. Whereas typically a char is used and each character is 1 byte.

Is there a good way to extract the "string" 'hello' and put it into a char[] so it can be printed out later? Iterate over the unsigned short array and store the value into a char array?

CodePudding user response:

How to convert?:

char b[6];
for(size_t i = 0; i < 5; i  ) b[i] = a[i];
b[5] = 0;
  • Related