Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++의 2진법을 10진법으로 변환하는 프로그램

<시간/>

2진수를 입력으로 하여 주어진 2진수를 10진수로 변환하는 작업입니다.

컴퓨터의 10진수는 10진법으로 표시되고 2진법은 2진법 0과 1의 두 자리만 있기 때문에 2진법으로 표시되지만 십진수는 0 – 9부터 시작하는 모든 숫자가 될 수 있습니다.

이진수를 십진수로 변환하려면 나머지를 통해 오른쪽에서 왼쪽으로 시작하는 자릿수를 추출한 다음 0에서 시작하여 2의 거듭제곱으로 곱하고 (자릿수) - 1이 될 때까지 1씩 증가합니다. 최종 소수점 값을 얻기 위해 곱한 값을 계속 추가합니다.

아래는 2진수를 10진수로 변환한 그림입니다.

C++의 2진법을 10진법으로 변환하는 프로그램

예시

Input-: 1010
   0 will be converted to a decimal number by -: 0 X 2^0 = 0
   1 have corresponding binary equivalent of 3 digit -: 1 X 2^1 = 2
   0 have corresponding binary equivalent of 3 digit -: 0 X 2^2 = 0
   1 have corresponding binary equivalent of 3 digit -: 1 X 2^3 = 8
Output-: total = 0 + 2 + 0 + 8 = 10

알고리즘

Start
Step1-> Declare function to convert binary to decimal
   int convert(string str)
   set string n = str
   set int val = 0
   set int temp = 1
   set int len = n.length()
   Loop For int i = len - 1 i >= 0 i—
      IF n[i] == '1'
         Set val += temp
      End
      Set temp = temp * 2
   End
   return val
Step 2-> In main()
   Set string val = "11101"
   Call convert(val)
Stop

예시

#include <iostream>
#include <string>
using namespace std;
//convert binary to decimal
int convert(string str) {
   string n = str;
   int val = 0;
   int temp = 1;
   int len = n.length();
   for (int i = len - 1; i >= 0; i--) {
      if (n[i] == '1')
      val += temp;
      temp = temp * 2;
   }
   return val;
}
int main() {
   string val = "11101";
   cout<<val<<" after converion into deciaml : "<<convert(val);
}

출력

위의 코드를 실행하면 다음 출력이 생성됩니다.

11101 after converion into deciaml : 29