C / C ++에서 ITOA를 사용하여 정수를 바이너리 문자열로 변환
문제
Long Long int를 바이너리 문자열로 변환하려면 itoa()
를 사용할 수 있습니까?
itoa
를 사용하여 int를 바이너리로 변환하기위한 다양한 예제를 보았습니다.긴 int를 사용하면 오버플로 또는 정밀도가 손실 될 위험이 있습니다.
편집 - 여러분 모두에게 답장을 보내주십시오.나는 내가하려고했던 것을 달성했다.iToA ()는 긴 int를 지원하지 않으므로 충분히 유용하지 않았습니다.
해결책
정수를 바이너리 숫자 만 포함하는 문자열로 변환하려면 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에서 모두 지원됩니다.
다른 팁
예, 당신이 할 수 있습니다. intoa를 표시 할 수 있습니다. 이는 바이너리를 의미합니다..
#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;
}
.
또한 ITO ()는 일반 "int"만 값으로 사용하기 때문에 int보다 큰 정수 유형을 사용하는 경우 잘림이있을 것입니다.int는 아마도 64 비트 일 것입니다. int는 아마도 64 비트에 있습니다. 그래서 컴파일러는 변환하기 전에 64 비트 값을 32 비트 값으로 자릅니다.
당신의 말씀은 조금 혼란 스럽습니다. 일반적으로 '십진법'을 나타내는 경우 : '소수 자리 문자열'으로 표시되는 숫자 '를 의미하는 동안'정수 '를 의미하는 것 같습니다.
와 '바이너리'를 사용하면 다음을 의미합니다. 'CPU가 직접 사용할 수있는 바이트로 표시되는 숫자입니다.
주제를 더 잘 표현할 수있는 방법은 다음과 같습니다. 64 비트 정수를 바이너리 숫자의 문자열로 변환합니다.
일부 시스템에는 _i64toa 함수가 있습니다.
long long
로 변환하는 표준 방법은 strtoull()
및 std::strtoull()
각각 C 및 C ++의
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';
}
}
.