Convert char pointer to unsigned array

I want to convert a char pointer to an unsigned char var, I thought I could do it with just casting, but it doesn't work:

char * pch2; //Code that puts something in pc2 part1 = (unsigned char) pch2; 

I have a code:

 result.part1 = (unsigned char *) pch2; printf("STRUCT %s\n",result.part1); 

the result is just a structure with unsigned char arrays.

EDIT:

  pch2 = strtok( ip, "." ); while( pch2 != NULL ){ printf( "x %dx: %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; 
+7
source share
5 answers

you added unsigned char not unsigned char* , you forgot *

 part1 = (unsigned char*) pch2; 

if pch2 does not have zero completion, the program will crash if you are lucky when you use strlen , so you need to discard it before printing before printing with pch2 , try this instead:

 pch2[size-1] = '\0'; /* note single quote */ result.part1 = (unsigned char *) pch2; 

Update: Define your structure as follows:

 typedef struct { const char *part1; const char *part2 const char *part3; const char *part4; } res; 

And assign it without casting at all:

 result.part1 = pch2; 
+3
source

You want to do this:

 part1 = (unsigned char*) pch2; 

Instead:

 part1 = (unsigned char) pch2; 
+1
source

Try something like this: -

  char *ph2; unsigned char *new_pointer = (unsigned char*) ph2; 
+1
source

I want to convert char pointer to unsigned char var

Are you sure? Converting a pointer from char to an unsigned char will not do any good - the value will be truncated to 1 byte, and in any case it will be meaningless. Perhaps you want to dereference the pointer and get the value indicated by it, then you should do something like this:

 unsigned char part1 = (unsigned char)*pch2; 

After your editing, I see that part1 is an array of characters - if your program crashes after using it, you are probably filling pch2 . Maybe you forgot the terminator '\0' ?

EDIT:

You see, now it is much better to answer your question, having all the necessary information. Do you need to use strtok ? Would that be good?

  res result; char* ip = "123.23.56.33"; sscanf(ip, "%hhu.%hhu.%hhu.%hhu", &result.part1, &result.part2, &result.part3, &result.part4); 
+1
source

Found a problem, forgot to give char pch2 an unsigned int, and then print with% u. The code:

 unsigned int temp; temp = atoi(pch2); result.part1 = temp; printf("Struct: %u\n",result.part1); 

Thanks for the help guys!

0
source

All Articles