简体   繁体   English

无符号短数组到字符数组

[英]Unsigned Short Array to Char Array

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.但我很好奇人们如何将无符号短数组中的字符串转换或提取为字符数组,以便在printf() 中用于调试目的。

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.根据我最近的理解,一个 unsigned short 是 2 个字节,所以 'h' 有一个 Null 终止符。 Whereas typically a char is used and each character is 1 byte.而通常使用 char 并且每个字符是 1 个字节。

Is there a good way to extract the "string" 'hello' and put it into a char[] so it can be printed out later?有没有一种好方法可以提取“字符串” 'hello' 并将其放入 char[] 以便稍后打印出来? Iterate over the unsigned short array and store the value into a char array?迭代无符号短数组并将值存储到字符数组中?

How to convert?:如何转换?:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM