Read unsigned chars into string
-
07-07-2021 - |
题
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.
Should I be looking at 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*?
其他提示
strcmp
and memcmp
compare data, they don't copy it...
Anyway, just cast to char *
and use whatever stdlib function makes sense.
If by string you mean a char array, the simplest way in c++ is just to use std::copy, no need to cast anything:
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 dest( buffer, buffer + N );
不隶属于 StackOverflow