How to convert a string into a byte array in C++ -


i trying convert string of length 128bytes byte array. eg: if string "76ab345fd77......" on. want convert byte array , should {76 ab 34 45 ....} , on upto 64 bytes. have written following code byte array shows value 1 instead of 76 ab .... suggestions doing wrong here or if there better way achieve this:

char* newsign; // contains "76ab345fd77...."       int len = strlen(newsign); //len 128 int num = len/2; pbyte bsign; //allocate signature buffer bsign = (pbyte)heapalloc (getprocessheap (), 0, num); if(null == bsign) {     wprintf(l"**** memory allocation failed\n");     return; } int i,n; for(i=0,n=0; n<num ;i=i+2,n++) {     bsign[n]=((newsign[i]<<4)||(newsign[i+1]));     printf("newsign[%d] %c , newsign[%d] %c\n",i,newsign[i],i+1,newsign[i+1]);     printf("bsign[%d] %x\n",n,bsign[n]);     //sprintf(bsign,"%02x",()newsign[i]); } 

thanks lot replies. following code worked me:

byte ascii_to_num(char c) {     if ('0' <= c && c <= '9')  return c - '0';  if ('a' <= c && c <= 'f')  return  c -('a'-('0'+10)); } for(i=0,n=0; n<num ;i=i+2,n++)     {         byte = (ascii_to_num(newsign[i])) & 0x0f;         byte b = ascii_to_num(newsign[i+1]) & 0x0f;         bsign[n] = (a<<4) | (b);         printf("bsign[%d] %x\n",n,bsign[n]);         } 

the code:

bsign[n]=((newsign[i]<<4)||(newsign[i+1])); 

will not convert hex characters byte. note want bitwise or | instead of logical or ||. decimal digits it's more like

bsign[n]=(((newsign[i]-'0')<<4)|((newsign[i+1]-'0')); 

but need take care of a-f values. you'll want write function turn hex character value

eg.

int hextoval(char c) {     c = (c | 0x20) - '0';     if (c<0) error;     if (c>9) {         c -= ('a'-('0'+10));         if (c<10 || c>15) error;     }      return c; }      bsign[n]=((hextoval(newsign[i])<<4)|hextoval(newsign[i+1])); 

Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -