简体   繁体   中英

How to convert an unsigned char* into char*

I want to convert unsigned char* to char*, print the value and again convert char* to unsigned char*. How can I do that ?

Byte arrays can be interpreted as arrays of char , unsigned char or signed char .

Most string functions from the C library take arguments of type char * or const char * and assume the arrays pointed to by such pointers have a null terminator (a null byte indicating the end if the string, conventionally written as a the null character constant '\\0' ).

As long as your array of unsigned char has a null terminator, it is harmless to cast its address as (char *) or (const char *) when passing it to these library functions.

For example:

#include <stdio.h>
#include <string.h>

int main(void) {
    unsigned char buf[256];
    char *p;

    for (size_t i = 0; i < sizeof(buf); i++) {
        buf[i] = (i + 1) & 255;
    }
    printf("length of array: %d\n", (int)strlen((char *)buf));
    printf("complete character set: >>>%s<<<\n", (char *)buf);

    p = (char *)buf;
    printf("char type is %s by default\n", p[128] < 0 ? "signed" : "unsigned");
    return 0;
}
unsigned char x = 0xFF;
unsigned char *p = &x;

printf("Signed value - %d\n", *((char *)p));
printf("Unsigned value - %u\n", *p);

But I agree with commenter that such casting should be avoided if possible.

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