Convert hex char[] to int[] in C 2 chars in 1 byte -


i trying convert char[] in hexadecimal format int[] in hexadecimal.

something this:

hello --> 68656c6c6f --> [68, 65, 6c, 6c, 6f]

this code:

#include <stdio.h> #include <string.h>  uint8_t* hex_decode(unsigned char *in, size_t len, uint8_t *out);  int main(void){ unsigned char  word_in[17], word_out[33];//17:16+1, 33:16*2+1 int i, len = 0; uint8_t* out;   while(len != 16){     printf("set new word:");     fgets( word_in, sizeof( word_in), stdin);     len = strlen( word_in);     if( word_in[len-1]=='\n')         word_in[--len] = '\0';      for(i = 0; i<len; i++){         sprintf(word_out+i*2, "%02x",  word_in[i]);     }     if(len != 16){         printf("please, use word of 16 chars long\n\n");     } } printf("%s", word_in); printf("\n");  hex_decode(word_out, sizeof(word_out), out);  return 0; }  uint8_t* hex_decode(unsigned char *in, size_t len, uint8_t *out) {     unsigned int i, t, hn, ln;      (t = 0,i = 0; < len; i+=2,++t) {              hn = in[i] > '9' ? (in[i]|32) - 'a' + 10 : in[i] - '0';             ln = in[i+1] > '9' ? (in[i+1]|32) - 'a' + 10 : in[i+1] - '0';              out[t] = (hn << 4 ) | ln;             printf("%s",out[t]);     }     return out;  } 

but after printing word, got segmentation fault.

that function works perfect in arduino think should works fine @ computer... problem?

see @dasblinkenlight answer seg fault. decode 2 bytes:

my 50 cent... (a short version)

char hex[3]; char * phex; int result; for(int = 0; < 256; i++) {     sprintf(hex, "%02x", i);     phex = hex;     result = ((*phex > 64 ? (*phex & 0x7) + 9 : *phex - 48) << 4) | (*(phex+1) > 64 ? (*(phex+1) & 0x7) + 9 : *(phex+1) - 48);     if(result != i)     {         printf("err %s %02x\n", hex, result);     } } 

code above no validation. procedure returns -1 when input invalid.

int h2i(char * ph) {     int result;     if(*ph > 96 && *ph < 103) result = *ph - 87;     else if(*ph > 64 && *ph < 71) result = *ph - 55;     else if(*ph > 47 && *ph < 59) result = *ph - 48;     else return -1;     result <<= 4;     ph++;     if(*ph > 96 && *ph < 103) result |= *ph - 87;     else if(*ph > 64 && *ph < 71) result |= *ph - 55;     else if(*ph > 47 && *ph < 59) result |= *ph - 48;     else return -1;     return result; } 

but wait? char can -1. yes, after casting.

char * x = "ff"; char y; int result; result = h2i(x); // if (result == -1) ...error... y = (char)result; 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -