Reputation: 990
I want to convert unsigned char* to char*, print the value and again convert char* to unsigned char*. How can I do that ?
Upvotes: 1
Views: 14648
Reputation: 145317
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;
}
Upvotes: 2
Reputation: 667
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.
Upvotes: 0