char[] to hex string exercise

前端 未结 16 743
感情败类
感情败类 2021-01-12 19:14

Below is my current char* to hex string function. I wrote it as an exercise in bit manipulation. It takes ~7ms on a AMD Athlon MP 2800+ to hexify a 10 million byte array. Is

16条回答
  •  北恋
    北恋 (楼主)
    2021-01-12 19:57

    Faster C Implmentation

    This runs nearly 3x faster than the C++ implementation. Not sure why as it's pretty similar. For the last C++ implementation that I posted it took 6.8 seconds to run through a 200,000,000 character array. The implementation took only 2.2 seconds.

    #include 
    #include 
    
    char* char_to_hex(const unsigned char* p_array, 
                      unsigned int p_array_len,
                      char** hex2ascii)
    {
        unsigned char* str = malloc(p_array_len*2+1);
        const unsigned char* p_end = p_array + p_array_len;
        size_t pos=0;
        const unsigned char* p;
        for( p = p_array; p != p_end; p++, pos+=2 ) {
           str[pos] = hex2ascii[*p][0];
           str[pos+1] = hex2ascii[*p][1];
        }
        return (char*)str;
    }
    
    int main()
    {
      size_t hex2ascii_len = 256;
      char** hex2ascii;
      int i;
      hex2ascii = malloc(hex2ascii_len*sizeof(char*));
      for(i=0; i

    enter image description here

提交回复
热议问题