Pregunta

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()?

¿Fue útil?

Solución

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*?

Otros consejos

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 );
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top