[英]Read unsigned chars into string
I have an array of unsigned chars: 我有一个未签名的字符数组:
unsigned char buffer[BUFFER_SIZE];
I want to read in the first N unsigned chars from that array into a string however after looking at strncpy()
, that seems to only take pointers to signed chars. 我想从该数组中将前N个未签名的字符读入字符串,但是在查看strncpy()
之后,似乎只采用了指向已签名字符的指针。
Should I be looking at memcpy()
? 我应该看memcpy()
吗?
Not sure about the exact syntax but, if possible, you should use: 不确定确切的语法,但如果可能,应使用:
reinterpret_cast<char *>(buffer[i]);
Also see: 另请参阅:
Is there a good way to convert from unsigned char* to char*? 有没有从unsigned char *转换为char *的好方法?
strcmp
and memcmp
compare data, they don't copy it... strcmp
和memcmp
比较数据,他们不复制数据...
Anyway, just cast to char *
and use whatever stdlib function makes sense. 无论如何,只要将其强制转换为char *
并使用任何有意义的stdlib函数即可。
If by string you mean a char array, the simplest way in c++ is just to use std::copy, no need to cast anything: 如果用字符串表示一个char数组,则c ++中最简单的方法就是使用std :: copy,而无需强制转换任何内容:
unsigned char buffer[BUFFER_SIZE];
char dest[BUFFER_SIZE]
std::copy( buffer, buffer + N, dest );
If you mean a std::string, just use the iterator style constructor: 如果您指的是std :: string,则只需使用迭代器样式构造函数即可:
std::string dest( buffer, buffer + N );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.