Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

Yes, you can. As you showed yourself, itoa can be called with base 2, which means binary.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i;
    char str[33];

    i = 37; /* Just some number. */
    itoa (i, str, 2);
    printf("binary: %s\n", str);

    return 0;
}

Also, yes, there will be truncation if you use an integer type larger than int, since itoa() takes only plain "int" as a value. long long is on your compiler probably 64 bit while int is probably 32 bit, so the compiler would truncate the 64 bit value to a 32 bit value before conversion.

your wording is a bit confusing, normally if you state 'decimal' i would take that to mean: 'a number represented as a string of decimal digits', while you seem to mean 'integer'.

and with 'binary' i would take that to mean: 'a number represented as bytes - as directly usable by the cpu'.

a better way of phrasing your subject would be: converting 64 bit integer to string of binary digits.

some systems have a _i64toa function.

The standard way to convert to long long is strtoull() and std::strtoull() for C and C++ respectively

Example on cppreference

#include <iostream>
#include <cstdlib>

int main()
{
    const char* begin = "10 200000000000000000000000000000 30 40";
    char *end;
    for (unsigned long i = std::strtoul(begin, &end, 10);
         begin != end;
         i = std::strtoul(begin, &end, 10))
    {
        begin = end;
        if (errno == ERANGE){
            std::cout << "range error\n";
            errno = 0;
        }    
        std::cout << i << '\n';
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top