简体   繁体   中英

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.

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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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