How to convert large bitsets ie bitset<256> into hexadecimal in C++?

138 views Asked by At

I have a large bitset<256> that I want to convert to hexadecimal but common solutions of to_ulong() and to_ullong() throws overflow error.

        bitset<256> bitresult = to_bitset(hexToBinary(x2)) ^ to_bitset(hexToBinary(random[i-1]));
            stringstream res;

            bitset<64> b1;
            bitset<64> b2;
            bitset<64> b3;
            bitset<64> b4;

            for (int i1=0; i1<64; i1++)
            b1[i1]=bitresult[i1];
            for (int i1=0; i1<64; i1++)
            b2[i1]=bitresult[i1+64];
            for (int i1=0; i1<64; i1++)
            b3[i1]=bitresult[i1+128];
            for (int i1=0; i1<64; i1++)
            b4[i1]=bitresult[i1+192];

            res<< hex << b1.to_ullong();
            res<< hex << b2.to_ullong();
            res<< hex << b3.to_ullong();
            res<< hex << b4.to_ullong();
            string hashresult = res.str();
            cout << hashresult <<endl;
                 return sha256(hashresult);

However I am having issues returning them back to Hexadecimal, due to the large size, to.ullong() throws overflow error. The code above is my attempt but for me seems very flawed, is there a better solution to this ?

1

There are 1 answers

0
Andrés Alcarraz On

Not much different to what you did, but more generic, and it would work with sizes of unsigned long long:

template <std::size_t N>
std::string bitset_to_hex(const std::bitset<N> &bs) {
    std::ostringstream os;
    static const std::bitset<N> MASK {(unsigned long long)-1};// all FFs
    static const std::size_t BITS_PER_NUMBER = sizeof(unsigned long long)*8; //bits per unsigned long long
    for (int i = BITS_PER_NUMBER; i<=N; i+=BITS_PER_NUMBER) {
        os << std::hex << std::setfill('0') << std::setw(BITS_PER_NUMBER/4) << ( (bs>>(N-i)) & MASK).to_ullong();
    }   
    return os.str();
}

You then just call it:

return sha256(bitset_to_hex);