Convert char array to hex array (C++)

前端 未结 2 1468
[愿得一人]
[愿得一人] 2021-01-29 16:17

My problem is converting array of chars to array of hexadecimal numbers, i need to take 2chars from char array and conver them into one hex number.

This is my input:

2条回答
  •  耶瑟儿~
    2021-01-29 17:02

    Some easy implementations

    unsigned char text[1024] = "06fb7405eba8d9e94fb1f28f0dd21fdec55fd54750ee84d95ecccf2b1b48";
    unsigned char result[512];
    
    int size = 60;
    
    assert(size % 2 == 0);
    
    for (int i = 0; i + 1 < size; i += 2)
    {
        std::string s(text + i, text + i + 2);
        auto x = std::stoi(s, 0, 16);
        result[i / 2] = x;
    }
    // or
    for (int i = 0; i + 1 < size; i += 2)
    {
        unsigned char c1 = *(text + i);
        unsigned char c2 = *(text + i + 1);
        char buffer[] = { c1, c2, 0 };
        auto x = std::strtol(buffer, 0, 16);
        result[i / 2] = x;
    }
    

    In this case the result is the half size of the input. Two chars are leading to one value in the result. If this is a time critical routine you may write your own conversion from two chars in a number.

提交回复
热议问题