Converting integer to binary string using itoa in C/C++

Mayank Kataria picture Mayank Kataria · Mar 14, 2012 · Viewed 11.5k times · Source

Can I use itoa() for converting long long int to a binary string?

I have seen various examples for conversion of int to binary using itoa. Is there a risk of overflow or perhaps loss of precision, if I use long long int?

Edit

Thanks all of you for replying. I achieved what I was trying to do. itoa() was not useful enough, as it does not support long long int. Moreover I can't use itoa() in gcc as it is not a standard library function.

Answer

Some programmer dude picture Some programmer dude · Mar 14, 2012

To convert an integer to a string containing only binary digits, you can do it by checking each bit in the integer with a one-bit mask, and append it to the string.

Something like this:

std::string convert_to_binary_string(const unsigned long long int value,
                                     bool skip_leading_zeroes = false)
{
    std::string str;
    bool found_first_one = false;
    const int bits = sizeof(unsigned long long) * 8;  // Number of bits in the type

    for (int current_bit = bits - 1; current_bit >= 0; current_bit--)
    {
        if ((value & (1ULL << current_bit)) != 0)
        {
            if (!found_first_one)
                found_first_one = true;
            str += '1';
        }
        else
        {
            if (!skip_leading_zeroes || found_first_one)
                str += '0';
        }
    }

    return str;
}

Edit:

A more general way of doing it might be done with templates:

#include <type_traits>
#include <cassert>

template<typename T>
std::string convert_to_binary_string(const T value, bool skip_leading_zeroes = false)
{
    // Make sure the type is an integer
    static_assert(std::is_integral<T>::value, "Not integral type");

    std::string str;
    bool found_first_one = false;
    const int bits = sizeof(T) * 8;  // Number of bits in the type

    for (int current_bit = bits - 1; current_bit >= 0; current_bit--)
    {
        if ((value & (1ULL << current_bit)) != 0)
        {
            if (!found_first_one)
                found_first_one = true;
            str += '1';
        }
        else
        {
            if (!skip_leading_zeroes || found_first_one)
                str += '0';
        }
    }

    return str;
}

Note: Both static_assert and std::is_integral is part of C++11, but is supported in both Visual C++ 2010 and GCC from at least 4.4.5.