3

itoa()long long int をバイナリ文字列に変換するために使用できますか?

を使用して int をバイナリに変換するさまざまな例を見てきましitoaた。long long int を使用すると、オーバーフローや精度の低下のリスクはありますか?

編集

返信ありがとうございます。私は自分がやろうとしていたことを達成しました。itoa()long long int をサポートしていないため、あまり役に立ちませんでした。さらにitoa()、標準ライブラリ関数ではないため、gcc では使用できません。

4

4 に答える 4

5

整数を 2 進数のみを含む文字列に変換するには、整数の各ビットを 1 ビット マスクでチェックし、それを文字列に追加します。

このようなもの:

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;
}

編集:

それを行うより一般的な方法は、テンプレートを使用して行うことができます。

#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;
}

注:static_assertstd::is_integralはどちらも C++11 の一部ですが、4.4.5 以降の Visual C++ 2010 と GCC の両方でサポートされています。

于 2012-03-14T09:30:28.987 に答える
3

はい、できます。あなたが自分自身を示したように、itoaはバイナリを意味するベース2で呼び出すことができます。

#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;
}

また、int より大きい整数型を使用すると切り捨てが発生します。これは、itoa() が値としてプレーンな「int」のみを受け取るためです。long long はコンパイラ上でおそらく 64 ビットですが、int はおそらく 32 ビットであるため、コンパイラは変換前に 64 ビット値を 32 ビット値に切り捨てます。

于 2012-03-14T09:48:43.527 に答える
1

あなたの言い回しは少し混乱しています。通常、「10 進数」と言うと、「 10 進数の文字列として表される数値」を意味すると解釈されますが、 「整数」を意味しているように見えます。

「バイナリ」を使用すると、「バイトとして表される数値-CPUが直接使用できる」という意味になります。

あなたの主題を表現するより良い方法は、64 ビット整数を 2 進数の文字列に変換することです。

一部のシステムには_i64toa機能があります。

于 2012-03-14T09:51:04.643 に答える
0

std::bitsetこの目的で使用できます

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);
于 2014-12-08T11:57:45.263 に答える