IT Share you

C ++-십진수를 이진으로 변환

shareyou 2020. 12. 2. 22:11
반응형

C ++-십진수를 이진으로 변환


10 진수를 이진수로 변환하는 '간단한'(30 분 걸림) 프로그램을 작성했습니다. 훨씬 더 간단한 방법이 있다고 확신하므로 보여줄 수 있습니까? 코드는 다음과 같습니다.

#include <iostream>
#include <stdlib.h>

using namespace std;
int a1, a2, remainder;
int tab = 0;
int maxtab = 0;
int table[0];
int main()
{
    system("clear");
    cout << "Enter a decimal number: ";
    cin >> a1;
    a2 = a1; //we need our number for later on so we save it in another variable

    while (a1!=0) //dividing by two until we hit 0
    {
        remainder = a1%2; //getting a remainder - decimal number(1 or 0)
        a1 = a1/2; //dividing our number by two
        maxtab++; //+1 to max elements of the table
    }

    maxtab--; //-1 to max elements of the table (when dividing finishes it adds 1 additional elemnt that we don't want and it's equal to 0)
    a1 = a2; //we must do calculations one more time so we're gatting back our original number
    table[0] = table[maxtab]; //we set the number of elements in our table to maxtab (we don't get 10's of 0's)

    while (a1!=0) //same calculations 2nd time but adding every 1 or 0 (remainder) to separate element in table
    {
        remainder = a1%2; //getting a remainder
        a1 = a1/2; //dividing by 2
        table[tab] = remainder; //adding 0 or 1 to an element
        tab++; //tab (element count) increases by 1 so next remainder is saved in another element
    }

    tab--; //same as with maxtab--
    cout << "Your binary number: ";

    while (tab>=0) //until we get to the 0 (1st) element of the table
    {
        cout << table[tab] << " "; //write the value of an element (0 or 1)
        tab--; //decreasing by 1 so we show 0's and 1's FROM THE BACK (correct way)
    }

    cout << endl;
    return 0;
}

그건 그렇고 복잡하지만 최선을 다했습니다.

편집-다음은 내가 사용한 솔루션입니다.

std::string toBinary(int n)
{
    std::string r;
    while(n!=0) {r=(n%2==0 ?"0":"1")+r; n/=2;}
    return r;
}

std::bitset선행 0 패딩을 사용하여 바이너리로 된 텍스트 표현 .to_string()을 반환 하는 메서드가 std::string있습니다.

데이터에 필요한대로 bitset의 너비를 선택합니다. 예 std::bitset<32>들어 32 비트 정수에서 32 자 문자열을 가져옵니다.

#include <iostream>
#include <bitset>

int main()
{
    std::string binary = std::bitset<8>(128).to_string(); //to binary
    std::cout<<binary<<"\n";

    unsigned long decimal = std::bitset<8>(binary).to_ulong();
    std::cout<<decimal<<"\n";
    return 0;
}

편집 : Octal 및 Hexadecimal에 대한 내 대답을 편집하지 마십시오. OP는 특히 Decimal To Binary를 요청했습니다.


다음은 양의 정수를 받아 2 진수를 콘솔에 출력하는 재귀 함수입니다.

Alex는 효율성을 위해 printf()결과 를 제거 하고 메모리에 저장하는 것이 좋습니다. 저장 방법에 따라 결과가 반전 될 수 있습니다.

/**
 * Takes a unsigned integer, converts it into binary and prints it to the console.
 * @param n the number to convert and print
 */
void convertToBinary(unsigned int n)
{
    if (n / 2 != 0) {
        convertToBinary(n / 2);
    }
    printf("%d", n % 2);
}

UoA ENGGEN 131에 대한 크레딧

* 참고 : unsigned int를 사용하는 이점은 음수가 될 수 없다는 것입니다.


std :: bitset을 사용하여 숫자를 이진 형식으로 변환 할 수 있습니다.

다음 코드 스 니펫을 사용하세요.

std::string binary = std::bitset<8>(n).to_string();

나는 이것을 stackoverflow 자체에서 발견했습니다. 링크를 첨부하고 있습니다.


바이너리를 인쇄하는 매우 간단한 솔루션 :

#include <iostream.h>

int main()
{
 int num,arr[64];
 cin>>num;
 int i=0,r;
 while(num!=0)
{
  r = num%2;
  arr[i++] = r;
  num /= 2;
}

for(int j=i-1;j>=0;j--)
 cout<<arr[j];
}

비 재귀 솔루션 :

#include <iostream>
#include<string>


std::string toBinary(int n)
{
    std::string r;
    while(n!=0) {r=(n%2==0 ?"0":"1")+r; n/=2;}
    return r;
}
int main()
{
    std::string i= toBinary(10);
    std::cout<<i;
}

재귀 솔루션 :

#include <iostream>
#include<string>

std::string r="";
std::string toBinary(int n)
{
    r=(n%2==0 ?"0":"1")+r;
    if (n / 2 != 0) {
        toBinary(n / 2);
    }
    return r;
}
int main()
{
    std::string i=toBinary(10);
    std::cout<<i;
}

int변수는 이진의 진수가 아닙니다. 찾고있는 것은 숫자의 이진 문자열 표현으로, 개별 비트를 필터링하는 마스크를 적용한 다음 인쇄하여 얻을 수 있습니다.

for( int i = sizeof(value)*CHAR_BIT-1; i>=0; --i)
    cout << value & (1 << i) ? '1' : '0';

귀하의 질문이 알고리즘이라면 그것이 해결책입니다. 그렇지 않은 경우 std :: bitset 클래스를 사용하여 이를 처리해야합니다.

bitset< sizeof(value)*CHAR_BIT > bits( value );
cout << bits.to_string();

두 가지 접근 방식이 있습니다. 하나는 당신의 접근 방식과 유사합니다

#include <iostream>
#include <string>
#include <limits>
#include <algorithm>

int main()
{
    while ( true )
    {
        std::cout << "Enter a non-negative number (0-exit): ";

        unsigned long long x = 0;
        std::cin >> x;

        if ( !x ) break;

        const unsigned long long base = 2;

        std::string s;
        s.reserve( std::numeric_limits<unsigned long long>::digits ); 

        do { s.push_back( x % base + '0' ); } while ( x /= base );

        std::cout << std::string( s.rbegin(), s.rend() )  << std::endl;
    }
}

다른 하나는 다른 사람들이 제안한대로 std :: bitset을 사용합니다.

#include <iostream>
#include <string>
#include <bitset>
#include <limits>

int main()
{
    while ( true )
    {
        std::cout << "Enter a non-negative number (0-exit): ";

        unsigned long long x = 0;
        std::cin >> x;

        if ( !x ) break;

        std::string s = 
            std::bitset<std::numeric_limits<unsigned long long>::digits>( x ).to_string();

        std::string::size_type n = s.find( '1' ); 
        std::cout << s.substr( n )  << std::endl;
    }
}

다음은 ints다양한 크기 로 사용할 수있는 최신 변형입니다 .

#include <type_traits>
#include <bitset>

template<typename T>
std::enable_if_t<std::is_integral_v<T>,std::string>
encode_binary(T i){
    return std::bitset<sizeof(T) * 8>(i).to_string();
}

다음과 같이하고 싶습니다.

cout << "Enter a decimal number: ";
cin >> a1;
cout << setbase(2);
cout << a1

사용 된 배열이없는 10 진수 * Oya 제작 :

저는 아직 초보자이므로이 코드는 루프와 변수 xD 만 사용합니다.

네가 좋아하길 바래. 이것은 아마도 그것보다 더 간단하게 만들 수 있습니다 ...

    #include <iostream>
    #include <cmath>
    #include <cstdlib>

    using namespace std;

    int main()
    {
        int i;
        int expoentes; //the sequence > pow(2,i) or 2^i
        int decimal; 
        int extra; //this will be used to add some 0s between the 1s
        int x = 1;

        cout << "\nThis program converts natural numbers into binary code\nPlease enter a Natural number:";
        cout << "\n\nWARNING: Only works until ~1.073 millions\n";
        cout << "     To exit, enter a negative number\n\n";

        while(decimal >= 0){
            cout << "\n----- // -----\n\n";
            cin >> decimal;
            cout << "\n";

            if(decimal == 0){
                cout << "0";
            }
            while(decimal >= 1){
                i = 0;
                expoentes = 1;
                while(decimal >= expoentes){
                    i++;
                    expoentes = pow(2,i);
                }
                x = 1;
                cout << "1";
                decimal -= pow(2,i-x);
                extra = pow(2,i-1-x);
                while(decimal < extra){
                    cout << "0";
                    x++;
                    extra = pow(2,i-1-x);
                }
            }
        }
        return 0;
    }

std::string컨테이너 로 사용하는 간단한 변환기 입니다. 음수 값을 허용합니다.

#include <iostream>
#include <string>
#include <limits>

int main()
{
    int x = -14;

    int n = std::numeric_limits<int>::digits - 1;

    std::string s;
    s.reserve(n + 1);

    do
        s.push_back(((x >> n) & 1) + '0');
    while(--n > -1);

    std::cout << s << '\n';
}

이것은 그 어느 때보 다 간단한 프로그램입니다

//Program to convert Decimal into Binary
#include<iostream>
using namespace std;
int main()
{
    long int dec;
    int rem,i,j,bin[100],count=-1;
    again:
    cout<<"ENTER THE DECIMAL NUMBER:- ";
    cin>>dec;//input of Decimal
    if(dec<0)
    {
        cout<<"PLEASE ENTER A POSITIVE DECIMAL";
        goto again;
    }
    else
        {
        cout<<"\nIT's BINARY FORM IS:- ";
        for(i=0;dec!=0;i++)//making array of binary, but reversed
        {
            rem=dec%2;
            bin[i]=rem;
            dec=dec/2;
            count++;
        }
        for(j=count;j>=0;j--)//reversed binary is printed in correct order
        {
            cout<<bin[j];
        }
    }
    return 0; 
}

사실 그렇게하는 아주 간단한 방법이 있습니다. 우리가하는 일은 매개 변수에 숫자 (int)가 주어진 재귀 함수를 사용하는 것입니다. 이해하기 매우 쉽습니다. 다른 조건 / 변형도 추가 할 수 있습니다. 다음은 코드입니다.

int binary(int num)
{
    int rem;
    if (num <= 1)
        {
            cout << num;
            return num;
        }
    rem = num % 2;
    binary(num / 2);
    cout << rem;
    return rem;
}

#include "stdafx.h"
#include<iostream>
#include<vector>
#include<cmath>

using namespace std;

int main() {
    // Initialize Variables
    double x;
    int xOct;
    int xHex;

    //Initialize a variable that stores the order if the numbers in binary/sexagesimal base
    vector<int> rem;

    //Get Demical value
    cout << "Number (demical base): ";
    cin >> x;

    //Set the variables
    xOct = x;
    xHex = x;

    //Get the binary value
    for (int i = 0; x >= 1; i++) {
        rem.push_back(abs(remainder(x, 2)));
        x = floor(x / 2);
    }

    //Print binary value
    cout << "Binary: ";
    int n = rem.size();
    while (n > 0) {
        n--;
        cout << rem[n];
    } cout << endl;

    //Print octal base
    cout << oct << "Octal: " << xOct << endl;

    //Print hexademical base
    cout << hex << "Hexademical: " << xHex << endl;

    system("pause");
    return 0;
}

#include <iostream>
using namespace std;

int main()
{  
    int a,b;
    cin>>a;
    for(int i=31;i>=0;i--)
    {
        b=(a>>i)&1;
        cout<<b;
    }
}

HOPE YOU LIKE THIS SIMPLE CODE OF CONVERSION FROM DECIMAL TO BINARY


  #include<iostream>
    using namespace std;
    int main()
    {
        int input,rem,res,count=0,i=0;
        cout<<"Input number: ";
        cin>>input;`enter code here`
        int num=input;
        while(input > 0)
        {
            input=input/2;  
            count++;
        }

        int arr[count];

        while(num > 0)
        {
            arr[i]=num%2;
            num=num/2;  
            i++;
        }
        for(int i=count-1 ; i>=0 ; i--)
        {
            cout<<" " << arr[i]<<" ";
        }



        return 0;
    }

std::string bin(uint_fast8_t i){return !i?"0":i==1?"1":bin(i/2)+(i%2?'1':'0');}

// function to convert decimal to binary
void decToBinary(int n)
{
    // array to store binary number
    int binaryNum[1000];

    // counter for binary array
    int i = 0;
    while (n > 0) {

        // storing remainder in binary array
        binaryNum[i] = n % 2;
        n = n / 2;
        i++;
    }

    // printing binary array in reverse order
    for (int j = i - 1; j >= 0; j--)
        cout << binaryNum[j];
}

참조 :-https: //www.geeksforgeeks.org/program-decimal-binary-conversion/

또는 기능 사용 :-

#include<bits/stdc++.h>
using namespace std;

int main()
{

    int n;cin>>n;
    cout<<bitset<8>(n).to_string()<<endl;


}

또는 왼쪽 시프트 사용

#include<bits/stdc++.h>
using namespace std;
int main()
{
    // here n is the number of bit representation we want 
    int n;cin>>n;

    // num is a number whose binary representation we want
    int num;
    cin>>num;

    for(int i=n-1;i>=0;i--)
    {
        if( num & ( 1 << i ) ) cout<<1;
        else cout<<0;
    }


}

이를 위해 C ++에서는 itoa () 함수를 사용할 수 있습니다.이 함수는 Decimal 정수를 2 진수, 10 진수, 16 진수 및 8 진수로 변환합니다.

#include<bits/stdc++.h>
using namespace std;
int main(){
 int a;    
 char res[1000];
 cin>>a;
 itoa(a,res,10);
 cout<<"Decimal- "<<res<<endl;
 itoa(a,res,2);
 cout<<"Binary- "<<res<<endl;
 itoa(a,res,16);
 cout<<"Hexadecimal- "<<res<<endl;
 itoa(a,res,8);
 cout<<"Octal- "<<res<<endl;return 0;
}

그러나 특정 컴파일러에서만 지원됩니다.

또한 볼 수 있습니다 : itoa- C ++ Reference


아래는 바이너리를 10 진수로 변환하고 다시 역으로 변환하는 간단한 C 코드입니다. 나는 대상이 임베디드 프로세서 및 개발 도구가 있던 다음 stdlib 있었다있는 프로젝트를 위해 오래 전에 쓴 방법 펌웨어 ROM 너무 큰 있습니다.

이것은 라이브러리를 사용하지 않으며 분할 또는 나머지 (%) 연산자 (일부 임베디드 프로세서에서 느림)를 사용하지 않으며 부동 소수점을 사용하지 않으며 테이블 조회도 사용하지도 않는 일반 C 코드입니다. BCD 산술을 에뮬레이트합니다. 이것이 사용하는 것은 유형 long long,보다 구체적으로 unsigned long long(또는 uint64)이므로 임베디드 프로세서 (및 함께 제공되는 C 컴파일러)가 64 비트 정수 산술을 수행 할 수없는 경우이 코드는 응용 프로그램에 적합하지 않습니다. 그렇지 않으면, 나는 (아마도 변경 한 후이입니다 생산 품질의 C 코드 생각 longint32unsigned long long에를 uint64). 2 ^ 32 개의 부호있는 정수 값에 대해 테스트하기 위해 밤새 실행했으며 어느 방향으로도 변환 오류가 없습니다.

실행 파일을 생성 할 수있는 C 컴파일러 / 링커가 있었고 stdlib (돼지) 없이도 할 수있는 일 해야했습니다. 그래서 전혀 printf()아니다 scanf(). 아니 심지어 sprintf()아니다 sscanf(). 그러나 우리는 여전히 사용자 인터페이스를 가지고 있었고 10 진수 숫자를 이진수로 변환해야했습니다. (우리는 또한 우리 자신 malloc()과 유사한 유틸리티와 우리 자신의 초월적인 수학 함수 도 만들었습니다 .)

내가 그것을 어떻게이 그래서합니다 ( main프로그램 및 다음 stdlib 호출, 내 Mac에서이 일을 테스트하기 위해이 있었다 하지 임베디드 코드). 또한 일부 오래된 개발 시스템은 " int64"및 " uint64"및 유사한 유형을 인식하지 못하기 때문에 유형 long longunsigned long long동일한 것으로 간주됩니다. 그리고 long32 비트로 가정합니다. 나는 그것을 먹을 수 있었다고 생각 typedef한다.

// returns an error code, 0 if no error,
// -1 if too big, -2 for other formatting errors
int decimal_to_binary(char *dec, long *bin)
    {
    int i = 0;

    int past_leading_space = 0;
    while (i <= 64 && !past_leading_space)        // first get past leading spaces
        {
        if (dec[i] == ' ')
            {
            i++;
            }
         else
            {
            past_leading_space = 1;
            }
        }
    if (!past_leading_space)
        {
        return -2;                                // 64 leading spaces does not a number make
        }
    // at this point the only legitimate remaining
    // chars are decimal digits or a leading plus or minus sign

    int negative = 0;
    if (dec[i] == '-')
        {
        negative = 1;
        i++;
        }
     else if (dec[i] == '+')
        {
        i++;                                    // do nothing but go on to next char
        }
    // now the only legitimate chars are decimal digits
    if (dec[i] == '\0')
        {
        return -2;                              // there needs to be at least one good 
        }                                       // digit before terminating string

    unsigned long abs_bin = 0;
    while (i <= 64 && dec[i] != '\0')
        {
        if ( dec[i] >= '0' && dec[i] <= '9' )
            {
            if (abs_bin > 214748364)
                {
                return -1;                                // this is going to be too big
                }
            abs_bin *= 10;                                // previous value gets bumped to the left one digit...                
            abs_bin += (unsigned long)(dec[i] - '0');     // ... and a new digit appended to the right
            i++;
            }
         else
            {
            return -2;                                    // not a legit digit in text string
            }
        }

    if (dec[i] != '\0')
        {
        return -2;                                // not terminated string in 64 chars
        }

    if (negative)
        {
        if (abs_bin > 2147483648)
            {
            return -1;                            // too big
            }
        *bin = -(long)abs_bin;
        }
     else
        {
        if (abs_bin > 2147483647)
            {
            return -1;                            // too big
            }
        *bin = (long)abs_bin;
        }

    return 0;
    }


void binary_to_decimal(char *dec, long bin)
    {
    unsigned long long acc;                // 64-bit unsigned integer

    if (bin < 0)
        {
        *(dec++) = '-';                    // leading minus sign
        bin = -bin;                        // make bin value positive
        }

    acc = 989312855LL*(unsigned long)bin;        // very nearly 0.2303423488 * 2^32
    acc += 0x00000000FFFFFFFFLL;                 // we need to round up
    acc >>= 32;
    acc += 57646075LL*(unsigned long)bin;
    // (2^59)/(10^10)  =  57646075.2303423488  =  57646075 + (989312854.979825)/(2^32)  

    int past_leading_zeros = 0;
    for (int i=9; i>=0; i--)            // maximum number of digits is 10
        {
        acc <<= 1;
        acc += (acc<<2);                // an efficient way to multiply a long long by 10
//      acc *= 10;

        unsigned int digit = (unsigned int)(acc >> 59);        // the digit we want is in bits 59 - 62

        if (digit > 0)
            {
            past_leading_zeros = 1;
            }

        if (past_leading_zeros)
            {
            *(dec++) = '0' + digit;
            }

        acc &= 0x07FFFFFFFFFFFFFFLL;    // mask off this digit and go on to the next digit
        }

    if (!past_leading_zeros)            // if all digits are zero ...
        {
        *(dec++) = '0';                 // ... put in at least one zero digit
        }

    *dec = '\0';                        // terminate string
    }


#if 1

#include <stdlib.h>
#include <stdio.h>
int main (int argc, const char* argv[])
    {
    char dec[64];
    long bin, result1, result2;
    unsigned long num_errors;
    long long long_long_bin;

    num_errors = 0;
    for (long_long_bin=-2147483648LL; long_long_bin<=2147483647LL; long_long_bin++)
        {
        bin = (long)long_long_bin;
        if ((bin&0x00FFFFFFL) == 0)
            {
            printf("bin = %ld \n", bin);        // this is to tell us that things are moving along
            }
        binary_to_decimal(dec, bin);
        decimal_to_binary(dec, &result1);
        sscanf(dec, "%ld", &result2);            // decimal_to_binary() should do the same as this sscanf()

        if (bin != result1 || bin != result2)
            {
            num_errors++;
            printf("bin = %ld, result1 = %ld, result2 = %ld, num_errors = %ld, dec = %s \n",
                bin, result1, result2, num_errors, dec);
            }
        }

    printf("num_errors = %ld \n", num_errors);

    return 0;
    }

#else

#include <stdlib.h>
#include <stdio.h>
int main (int argc, const char* argv[])
    {
    char dec[64];
    long bin;

    printf("bin = ");
    scanf("%ld", &bin);
    while (bin != 0)
        {
        binary_to_decimal(dec, bin);
        printf("dec = %s \n", dec);
        printf("bin = ");
        scanf("%ld", &bin);
        }

    return 0;
    }

#endif

#include <iostream>
#include <bitset>

#define bits(x)  (std::string( \
            std::bitset<8>(x).to_string<char,std::string::traits_type, std::string::allocator_type>() ).c_str() )


int main() {

   std::cout << bits( -86 >> 1 ) << ": " << (-86 >> 1) << std::endl;

   return 0;
}

좋아요 .. 저는 C ++를 처음 접했을지 모르지만 위의 예제가 제대로 작동하지 않는다고 생각합니다.

이 상황에 대한 나의 견해는 다음과 같습니다.

char* DecimalToBinary(unsigned __int64 value, int bit_precision)
{
    int length = (bit_precision + 7) >> 3 << 3;
    static char* binary = new char[1 + length];
    int begin = length - bit_precision;
    unsigned __int64 bit_value = 1;
    for (int n = length; --n >= begin; )
    {
        binary[n] = 48 | ((value & bit_value) == bit_value);
        bit_value <<= 1;
    }
    for (int n = begin; --n >= 0; )
        binary[n] = 48;

    binary[length] = 0;
    return binary;
}

@value = 확인중인 값.

@bit_precision = 확인할 가장 왼쪽 가장 높은 비트.

@Length = 최대 바이트 블록 크기. 예 : 7 = 1 Byte 및 9 = 2 Byte, 그러나 우리는 이것을 비트 형태로 표현하므로 1 Byte = 8 Bits입니다.

@binary = 우리가 설정하는 문자 배열을 호출하기 위해 내가 준 멍청한 이름. 모든 호출에서 다시 생성되지 않도록이를 정적으로 설정했습니다. 단순히 결과를 가져 와서 표시하는 경우 이것은 잘 작동하지만 UI에 여러 결과를 표시하고 싶다면 모두 마지막 결과로 표시됩니다. 이 문제는 정적을 제거하여 수정할 수 있지만 작업이 끝나면 [] 결과를 삭제해야합니다.

@begin = 이것은 우리가 확인하는 가장 낮은 인덱스입니다. 이 지점을 넘어서는 모든 것은 무시됩니다. 또는 두 번째 루프에 표시된대로 0으로 설정합니다.

@first loop-여기서 값을 48로 설정하고 기본적으로 (value & bit_value) == bit_value의 bool 값을 기반으로 0 또는 1에서 48을 추가합니다. 이것이 사실이면 char는 49로 설정됩니다. 이것이 false이면 char는 48로 설정됩니다. 그런 다음 bit_value를 이동하거나 기본적으로 2를 곱합니다.

@second loop-여기서 우리는 무시한 모든 인덱스를 48 또는 '0'으로 설정합니다.

몇 가지 예시 출력 !!!

int main()
{
    int val = -1;
    std::cout << DecimalToBinary(val, 1) << '\n';
    std::cout << DecimalToBinary(val, 3) << '\n';
    std::cout << DecimalToBinary(val, 7) << '\n';
    std::cout << DecimalToBinary(val, 33) << '\n';
    std::cout << DecimalToBinary(val, 64) << '\n';
    std::cout << "\nPress any key to continue. . .";
    std::cin.ignore();
    return 0;
}

00000001 //Value = 2^1 - 1
00000111 //Value = 2^3 - 1.
01111111 //Value = 2^7 - 1.
0000000111111111111111111111111111111111 //Value = 2^33 - 1.
1111111111111111111111111111111111111111111111111111111111111111 //Value = 2^64 - 1.

속도 테스트

원래 질문의 답변 : "Method : toBinary (int);"

실행 : 10,000, 총 시간 (밀리) : 4701.15, 평균 시간 (나노초) : 470114

내 버전 : "메서드 : DecimalToBinary (int, int);"

// 64 비트 정밀도 사용.

실행 : 10,000,000, 총 시간 (밀리) : 3386, 평균 시간 (나노초) : 338

// 1 비트 정밀도 사용.

실행 : 10,000,000, 총 시간 (밀리) : 634, 평균 시간 (나노초) : 63


#include <iostream>

// x is our number to test
// pow is a power of 2 (e.g. 128, 64, 32, etc...)
int printandDecrementBit(int x, int pow)
{
    // Test whether our x is greater than some power of 2 and print the bit
    if (x >= pow)
    {
        std::cout << "1";
        // If x is greater than our power of 2, subtract the power of 2
        return x - pow;
    }
    else
    {
        std::cout << "0";
        return x;
    }
}

int main()
{
    std::cout << "Enter an integer between 0 and 255: ";
    int x;
    std::cin >> x;

    x = printandDecrementBit(x, 128);
    x = printandDecrementBit(x, 64);
    x = printandDecrementBit(x, 32);
    x = printandDecrementBit(x, 16);

    std::cout << " ";

    x = printandDecrementBit(x, 8);
    x = printandDecrementBit(x, 4);
    x = printandDecrementBit(x, 2);
    x = printandDecrementBit(x, 1);

    return 0;
}

이것은 int의 바이너리 형태를 얻는 간단한 방법입니다. learncpp.com에 대한 크레딧. 나는 이것이 같은 지점에 도달하기 위해 다른 방법으로 사용될 수 있다고 확신합니다.


이 접근 방식에서 십진수는 문자열 형식의 각 이진수로 변환됩니다. 문자열 반환형 는 입력 값 이상의 범위를 처리 할 수 있기 때문에 선택된다.

class Solution {
public:
  string ConvertToBinary(int num) 
  {
    vector<int> bin;
    string op;
    for (int i = 0; num > 0; i++)
    {
      bin.push_back(num % 2);
      num /= 2;
    }
    reverse(bin.begin(), bin.end());
    for (size_t i = 0; i < bin.size(); ++i)
    {
      op += to_string(bin[i]);
    }
    return op;
  }
};

C ++에서 십진수를 이진으로 변환하는 방법. 그러나 우리는 mod를 사용하고 있기 때문에이 함수는 16 진법이나 8 진법의 경우에도 작동합니다. 비트를 지정할 수도 있습니다. 이 함수는 최하위 비트를 계속 계산하여 문자열 끝에 배치합니다. 이 방법과 비슷하지 않다면 vist 할 수 있습니다. https://www.wikihow.com/Convert-from-Decimal-to-Binary

#include <bits/stdc++.h>
using namespace std;

string itob(int bits, int n) {
    int c;
    char s[bits+1]; // +1 to append NULL character.

    s[bits] = '\0'; // The NULL character in a character array flags the end of the string, not appending it may cause problems.

    c = bits - 1; // If the length of a string is n, than the index of the last character of the string will be n - 1. Cause the index is 0 based not 1 based. Try yourself.

    do {
        if(n%2) s[c] = '1';
        else s[c] = '0';
        n /= 2;
        c--;
    } while (n>0);

    while(c > -1) {
        s[c] = '0';
        c--;
}

    return s;
}

int main() {
    cout << itob(1, 0) << endl; // 0 in 1 bit binary.
    cout << itob(2, 1) << endl; // 1 in 2 bit binary.
    cout << itob(3, 2) << endl; // 2 in 3 bit binary.
    cout << itob(4, 4) << endl; // 4 in 4 bit binary.
    cout << itob(5, 15) << endl; // 15 in 5 bit binary.
    cout << itob(6, 30) << endl; // 30 in 6 bit binary.
    cout << itob(7, 61) << endl; // 61 in 7 bit binary.
    cout << itob(8, 127) << endl; // 127 in 8 bit binary.
    return 0;
}

출력 :

0
01
010
0100
01111
011110
0111101
01111111

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

void Decimal2Binary(long value,char *b,int len)
{
    if(value>0)
    {
        do
        {
            if(value==1)
            {
                *(b+len-1)='1';
                break;
            }
            else
            {
                *(b+len-1)=(value%2)+48;
                value=value/2;
                len--;
            }
        }while(1);
    }
}
long Binary2Decimal(char *b,int len)
{
    int i=0;
    int j=0;
    long value=0;
    for(i=(len-1);i>=0;i--)
    {
        if(*(b+i)==49)
        {
            value+=pow(2,j);
        }
        j++;
    }
    return value;
}
int main()
{
    char data[11];//最後一個BIT要拿來當字串結尾
    long value=1023;
    memset(data,'0',sizeof(data));
    data[10]='\0';//字串結尾
    Decimal2Binary(value,data,10);
    printf("%d->%s\n",value,data);
    value=Binary2Decimal(data,10);
    printf("%s->%d",data,value);
    return 0;
}

참고 URL : https://stackoverflow.com/questions/22746429/c-decimal-to-binary-converting

반응형