3

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.

5
  • AFAIK, itoa converts an integer to a string..... Could you provide some sample code from those examples that you mentioned? Commented Mar 14, 2012 at 9:23
  • itoa is not a standard function. Also, do you mean you want to convert an integer to a string with only binary digits? Commented Mar 14, 2012 at 9:24
  • 1
    @SayemAhmed- Here's the link which says i can convert int to binary string.cplusplus.com/reference/clibrary/cstdlib/itoa Commented Mar 14, 2012 at 9:25
  • mask out the bits and construct a binary string yourself. Commented Mar 14, 2012 at 9:25
  • @JoachimPileborg - Yes, Exactly. Commented Mar 14, 2012 at 9:26

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

8 Comments

The leading zeros could be easily avoided. Just skip the 0s until we see the first 1 (when scanned from left to right).
@AndreasMagnusson Added argument to skip leading zeroes. :)
Thanks A lot Joachim Pileborg ! Modified your code so that i can use it in c and it worked like a charm ! :) :)
If doing a C version, you could change current_bit = 63 to current_bit = ((sizeof value) * 8) - 1
I don't see how the template version works, where does bits variable come from?
|
3

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.

Comments

1

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.

Comments

0

You can use std::bitset for this purpose

template<typename T>
inline std::string to_binary_string(const T value)
{
    return std::bitset<sizeof(T)>(value).to_string();
}

std::cout << to_binary_string(10240);
std::cout << to_binary_string(123LL);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.