C / C ++でITOAを使用したバイナリ文字列への整数を変換する
質問
長いLONG INTをバイナリ文字列に変換するためにitoa()
を使用できますか?
itoa
を使用して、INTをバイナリに変換するためのさまざまな例を見ました。長いLONG INTを使用している場合は、オーバーフローまたはおそらく精度の損失があります。
編集 - 返信のためにあなた全員に感謝します。私はしようとしていたことを達成しました。itoa()は長い長いintをサポートしていないため、十分に役立ちませんでした。標準ライブラリ関数ではないので、GCCでiToa()を使用できません。
解決
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_assert
とstd::is_integral
の両方がC ++ 11の一部ですが、Visual C ++ 2010とGCCの両方で少なくとも4.4.5からサポートされています。
他のヒント
はい、できます。 を表示した、Base 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;
}
.
また、iToa()が普通の「int」のみを値としてin intより大きい場合は、intより大きい整数型を使用すると、切り捨てがあります。intはおそらく32ビットですが、コンパイラの長い長いはおそらく64ビットであるため、コンパイラは変換前に64ビット値を32ビット値に切り捨てます。
あなたの文言は少し混乱しています、 通常、「10進数」を述べている場合、「整数」を意味するように思われる間、「10進数の桁数として表される番号」を意味します。
と「バイナリ」とは、「CPUによって直接使用可能なものとして表す数字」を意味するようになります。
件名に句を越えてより良い方法であろう:64ビット整数を2進数の文字列に変換する。
システム一部のシステムには_I64TOA関数があります。
long long
に変換する標準的な方法は、 strtoull()
と
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';
}
}
.