C·C++

10진법을 2진법으로 변환하기(C++)

10진법을 2진법으로 변환하기(C++) 대표 이미지
10진수로 입력받아 2진수로 출력해보자.


#include <iostream>
#include <windows.h>
#include <math.h>
using namespace std;
int main(){
   
    int t,a=1;//a는 이진수의 자릿수
   
    cin>>t;
   
    while(t>=pow(2,a)){//이진수의 자릿수를 구한다.2^a이 t를 넘어서는 순간의 a가 t의 자리 수이다.
               a++;
    }
   
    for(a;a>0;a--){//a 자리수는 1~a자리수만 봤을떄, 2^(a-1)보다 같거 크면 a자리수가 1 아니면 0. a부터 1자리까지 자릿수를 구한다.
                   if(pow(2,a-1)<=t){
                                     cout<<1;
                                     t-=pow(2,a-1);//해당 자리수를 1로 만들고 자릿수만큼의 수를 뺸다.
                   }else {
                         cout<<0;//해당 자릿수는 0이므로 뺄수있는 수가 없다.
                   }
    }
   
    cout<<endl;
   
    system("PAUSE");
   
    return 0;
}   

실행결과

21
10101
Press any key to continue . . .
또 다른 방법, int배열에 이진수를 저장한 다음 출력하기.


#include <iostream>
#include <windows.h>

using namespace std;

int main(){
   
    int t,d[100]={0},l=0;
   
    cin >> t;
   
    while(t>0){
               d[l++] = t%2;
               t/=2;//이러면 t의 자릿수가 하나 줄어들고 일의 자릿수는 정수화로 인해 사라진다. 
    }//while문을 통해 l은 d배열의 실질적 길이를 나타낸다.
   
    for(l;l>0;l--)cout << d[l-1];//배렬을 끝부분부터 거꾸로 출력한다.
   
    cout<<endl;
   
    system("PAUSE");
   
    return 0;
}
실행결과

31
11111
Press any key to continue . . .

댓글