Robert
Robert

Reputation: 337

C++ convert boost multiprecision int to 64 bit length hex

lets imagine that we have code:

boost::multiprecision::mpz_int one(1);

and I would like to convert that value to 64 bit (?) hex value so the result could be:

0000000000000000000000000000000000000000000000000000000000000001

I'm sure that the is solution of that but I'm not familiar with Boost

Example: I have value:

boost::multiprecision::mpz_int value(8612844778121073626993440829679478604092771119379437256704)

and I want create 64b hex from value,

I tried

printf("%064X\n", value);

but don't work

Upvotes: 0

Views: 1042

Answers (2)

havogt
havogt

Reputation: 2802

Even with the extra example it is still unclear what you want to do: a) Do you want to write the binary representation of the integer which you can think of as a string of 64 characters 0 or 1 as your first example suggests? b) Or do you want the hex representation which would be a 16 character string?

What do you want to do if your integer does not fit into 64 bit?

I assume you want to print the hex representation of the integer filled with zeros, i.e. (b). Then the solution is as easy as (you claim to use c++)

std::cout << std::setfill('0') << std::setw( 16 ) << std::hex << value;

However this solution does not cover the unspecified behaviour of overflowing the 64 bit and it does not cover negative numbers. For this you need to be more precise...


Update:

According to the comment the output should be a 64 character string which could represent a 256 bit integer. This can be accomplished with:

std::cout << std::setfill('0') << std::setw( 64 ) << std::hex << value;

Upvotes: 1

Simon Kraemer
Simon Kraemer

Reputation: 5670

I don't have boost available atm but you could write a small function that formats the type for you.

If boost::multiprecision::mpz_int supports bitshift and the & operator operator this might be a solution:

template<typename T>
std::string toHex64(const T& value, size_t padding = 1)
{
    using UT = typename std::make_unsigned_t<T>;
    std::string hex;
    UT uvalue = static_cast<UT>(value);
    bool bPositive = std::is_same<T, UT>::value || value == uvalue;
    while (uvalue > UT(0))
    {
        char current = uvalue & 0xF; uvalue >>= 4;
        hex += (current < 0xA) ? (current + '0') : ((current-10) + 'A');
    }
    if (hex.size() < padding)
    {
        if (bPositive)
        {
            hex += std::string(padding - hex.size(), '0');
        }
        else
        {
            hex += std::string(padding - hex.size(), 'F');
        }
    }
    std::reverse(hex.begin(), hex.end());
    return hex;
}

Upvotes: 0

Related Questions