I want to convert a char pointer to a unsigned char var, I thought I could do that with just casting but it doesn't work:
char * pch2;
//Code that puts something in pc2
part1 = (unsigned char) pch2;
I've the code to this:
result.part1 = (unsigned char *) pch2;
printf("STRUCT %s\n",result.part1);
result is just a struct with unsigned char arrays.
EDIT:
pch2 = strtok( ip, "." );
while( pch2 != NULL ){
printf( "x %d x: %s\n", i, pch2 );
pch2[size-1] = '\0';
if(i == 1)
result.part1 = (unsigned char *) pch2;
if(i == 2)
result.part2 = (unsigned char *) pch2;
if(i == 3)
result.part3 = (unsigned char *) pch2;
if(i == 4)
result.part4 = (unsigned char *) pch2;
i++;
pch2 = strtok (NULL,".");
}
printf("STRUCT %c\n",result.part1);
Struct:
typedef struct
{
unsigned char part1;
unsigned char part2;
unsigned char part3;
unsigned char part4;
} res;
unsigned char can hold values between 0 and 255. signed char can hold values between -127 and 127.
unsigned char is a character datatype where the variable consumes all the 8 bits of the memory and there is no sign bit (which is there in signed char). So it means that the range of unsigned char data type ranges from 0 to 255.
unsigned char is usually used for holding binary data where 0 is valid value and still part of your data. While working with "naked" unsigned char* you'll probably have to hold the length of your buffer. char is usually used for holding characters representing string and 0 is equal to '\0' (terminating character).
For the array, the total string is stored in the stack section, but for the pointer, the pointer variable is stored into stack section, and content is stored at code section. And the most important difference is that, we cannot edit the pointer type string.
you cast to unsigned char
not unsigned char*
you forgot the *
part1 = (unsigned char*) pch2;
if pch2
is not null terminated the program will crash, if you're lucky, when you use strlen
, so you need to null terminate it first before printing using pch2
, try this instead:
pch2[size-1] = '\0'; /* note single quote */
result.part1 = (unsigned char *) pch2;
Update: define your structure like so:
typedef struct
{
const char *part1;
const char *part2
const char *part3;
const char *part4;
} res;
And assign to it without casting at all:
result.part1 = pch2;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With