Hex to char array in C

后端 未结 11 1111
广开言路
广开言路 2020-11-30 09:04

Given a string of hex values i.e. e.g. \"0011223344\" so that\'s 0x00, 0x11 etc.

How do I add these values to a char array?

Equivalent to say:

<
相关标签:
11条回答
  • 2020-11-30 10:00

    I was searching for the same thing and after reading a lot, finally created this function. Thought it might help, someone

    // in = "63 09  58  81" 
    void hexatoascii(char *in, char* out, int len){
        char buf[5000];
        int i,j=0;
        char * data[5000];
        printf("\n size %d", strlen(in));
        for (i = 0; i < strlen(in); i+=2)
        {
            data[j] = (char*)malloc(8);
            if (in[i] == ' '){
                i++;
            }
            else if(in[i + 1] == ' '){
                i++;
            }
            printf("\n %c%c", in[i],in[i+1]);
            sprintf(data[j], "%c%c", in[i], in[i+1]);
            j++;
        }
    
        for (i = 0; i < j-1; i++){
            int tmp;
            printf("\n data %s", data[i] );
            sscanf(data[i], "%2x", &tmp);
            out[i] = tmp;
        }
        //printf("\n ascii value of hexa %s", out);
    }
    
    0 讨论(0)
  • 2020-11-30 10:02

    The best way I know:

    int hex2bin_by_zibri(char *source_str, char *dest_buffer)
    {
      char *line = source_str;
      char *data = line;
      int offset;
      int read_byte;
      int data_len = 0;
    
      while (sscanf(data, " %02x%n", &read_byte, &offset) == 1) {
        dest_buffer[data_len++] = read_byte;
        data += offset;
      }
      return data_len;
    }
    

    The function returns the number of converted bytes saved in dest_buffer. The input string can contain spaces and mixed case letters.

    "01 02 03 04 ab Cd eF garbage AB"

    translates to dest_buffer containing 01 02 03 04 ab cd ef

    and also "01020304abCdeFgarbageAB"

    translates as before.

    Parsing stops at the first "error" (non hex, non space).

    Note: also this is a valid string:

    "01 2 03 04 ab Cd eF garbage AB"

    and produces:

    01 02 03 04 ab cd ef

    0 讨论(0)
  • 2020-11-30 10:03
    {
        char szVal[] = "268484927472";
        char szOutput[30];
    
        size_t nLen = strlen(szVal);
        // Make sure it is even.
        if ((nLen % 2) == 1)
        {
            printf("Error string must be even number of digits %s", szVal);
        }
    
        // Process each set of characters as a single character.
        nLen >>= 1;
        for (size_t idx = 0; idx < nLen; idx++)
        {
            char acTmp[3];
            sscanf(szVal + (idx << 1), "%2s", acTmp);
            szOutput[idx] = (char)strtol(acTmp, NULL, 16);
        }
    }
    
    0 讨论(0)
  • 2020-11-30 10:05

    Fatalfloor...

    There are a couple of ways to do this... first, you can use memcpy() to copy the exact representation into the char array.

    You can use bit shifting and bit masking techniques as well. I'm guessing this is what you need to do as it sounds like a homework problem.

    Lastly, you can use some fancy pointer indirection to copy the memory location you need.

    All of these methods are detailed here:

    Store an int in a char array?

    0 讨论(0)
  • 2020-11-30 10:06

    If the string is correct and no need to keep its content then i would do it this way:

    #define hex(c) ((*(c)>='a')?*(c)-'a'+10:(*(c)>='A')?*(c)-'A'+10:*(c)-'0') 
    
    void hex2char( char *to ){
      for(char *from=to; *from; from+=2) *to++=hex(from)*16+hex(from+1);
      *to=0;
    }
    

    EDIT 1: sorry, i forget to calculate with the letters A-F (a-f)

    EDIT 2: i tried to write a more pedantic code:

    #include <string.h> 
    
    int xdigit( char digit ){
      int val;
           if( '0' <= digit && digit <= '9' ) val = digit -'0';
      else if( 'a' <= digit && digit <= 'f' ) val = digit -'a'+10;
      else if( 'A' <= digit && digit <= 'F' ) val = digit -'A'+10;
      else                                    val = -1;
      return val;
    }
    
    int xstr2str( char *buf, unsigned bufsize, const char *in ){
      if( !in ) return -1; // missing input string
    
      unsigned inlen=strlen(in);
      if( inlen%2 != 0 ) return -2; // hex string must even sized
    
      for( unsigned i=0; i<inlen; i++ )
        if( xdigit(in[i])<0 ) return -3; // bad character in hex string
    
      if( !buf || bufsize<inlen/2+1 ) return -4; // no buffer or too small
    
      for( unsigned i=0,j=0; i<inlen; i+=2,j++ )
        buf[j] = xdigit(in[i])*16 + xdigit(in[i+1]);
    
      buf[inlen/2] = '\0';
      return inlen/2+1;
    }

    Testing:

    #include <stdio.h> 
    
    char buf[100] = "test";
    
    void test( char *buf, const char *s ){
       printf("%3i=xstr2str( \"%s\", 100, \"%s\" )\n", xstr2str( buf, 100, s ), buf, s );
    }
    
    int main(){
      test( buf,      (char*)0   );
      test( buf,      "123"      );
      test( buf,      "3x"       );
      test( (char*)0, ""         );
      test( buf,      ""         );
      test( buf,      "3C3e"     );
      test( buf,      "3c31323e" );
    
      strcpy( buf,    "616263"   ); test( buf, buf );
    }

    Result:

     -1=xstr2str( "test", 100, "(null)" )
     -2=xstr2str( "test", 100, "123" )
     -3=xstr2str( "test", 100, "3x" )
     -4=xstr2str( "(null)", 100, "" )
      1=xstr2str( "", 100, "" )
      3=xstr2str( "", 100, "3C3e" )
      5=xstr2str( "", 100, "3c31323e" )
      4=xstr2str( "abc", 100, "abc" )
    
    0 讨论(0)
提交回复
热议问题