Search code examples
c++hexboolean-operations

Bitwise functions AND, OR and XOR using hexadecimal Strings in C ++


I have a function that accepts two string values ​​in hexadecimal and I need to make them the implement the boolean functions AND, OR and XOR, but my implementation does not deliver the expected values:

string A = "00000018631340800001";
string B = "FFFFFFFFFFFFFFE00000";

Expected answer of A & B = "00000018631340800000", but my function always gives "00000000000000000000".

Here is my snippet:

string funcion_and(string valor1, string valor2)
{
    int val_int[20 + 1] = {0};
    char valC[20 + 1] = {0};
    unsigned char valA[20 + 1] = {0};
    unsigned char valB[20 + 1] = {0};

    sscanf(valor1.c_str(), "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX",
    &valA[0], &valA[1], &valA[2], &valA[3], &valA[4], &valA[5], &valA[6], &valA[7], &valA[8], &valA[9]);

    sscanf(valor2.c_str(), "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX",
    &valB[0], &valB[1], &valB[2], &valB[3], &valB[4], &valB[5], &valB[6], &valB[7], &valB[8], &valB[9]);

    for(int i = 0; i < 10; i++)
    {
        val_int[i] = valA[i] & valB[i];
    }

    sprintf(valC, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", val_int[0], val_int[1], val_int[2], val_int[3], val_int[4], val_int[5], val_int[6], val_int[7], val_int[8], val_int[9]);

    return string(valC);
}

I know that I can also improve the code a lot, but I would like to know why it is not working.


Solution

  • Tried your code with VS2017 and it works. I suspect that your problem could come from sscanf or sprintf. You could alternately try using stringstream for the conversion:

    #include <sstream>
    #include <iomanip>
    
    /* size refers to the string size */
    std::string inthex_to_str(unsigned int i, unsigned int size)
    {
        std::stringstream stream;
        stream << std::setfill('0') << std::setw(size) << std::hex << i;
        return stream.str();
    }
    
    unsigned int str_to_inthex(string a)
    {
        unsigned int i;
        std::stringstream stream;
        stream << std::hex << a;
        stream >> i;
        return i;
    }
    
    string funcion1_and(string valor1, string valor2)
    {
        string str3 = "";
        for (int i = 0; i < valor1.size() - 1; i += 2)
        {
            unsigned int val1 = str_to_inthex(valor1.substr(i, 2));
            unsigned int val2 = str_to_inthex(valor2.substr(i, 2));
            str3 += inthex_to_str(val1 & val2, 2);
        }
        return str3;
    }