char[] to hex string exercise

前端 未结 16 738
感情败类
感情败类 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 20:00

    This is my version, which, unlike the OP's version, doesn't assume that std::basic_string has its data in contiguous region:

    #include 
    
    using std::string;
    
    static char const* digits("0123456789ABCDEF");
    
    string
    tohex(string const& data)
    {
        string result(data.size() * 2, 0);
        string::iterator ptr(result.begin());
        for (string::const_iterator cur(data.begin()), end(data.end()); cur != end; ++cur) {
            unsigned char c(*cur);
            *ptr++ = digits[c >> 4];
            *ptr++ = digits[c & 15];
        }
        return result;
    }
    

提交回复
热议问题