컴퓨터 시스템에서 2진수는 2진수 시스템으로 표현되고 10진수는 10진수 시스템으로 표현됩니다. 2진수는 2진수이고 10진수는 10진수입니다.
10진수 및 해당 2진수의 예는 다음과 같습니다. -
십진수 | 이진수 |
---|---|
10 | 01010 |
7 | 00111 |
25 | 11001 |
16 | 10000 |
2진수를 10진수로, 10진수를 2진수로 변환하는 프로그램은 다음과 같습니다.
예시
#include <iostream> using namespace std; void DecimalToBinary(int n) { int binaryNumber[100], num=n; int i = 0; while (n > 0) { binaryNumber[i] = n % 2; n = n / 2; i++; } cout<<"Binary form of "<<num<<" is "; for (int j = i - 1; j >= 0; j--) cout << binaryNumber[j]; cout<<endl; } int BinaryToDecimal(int n) { int decimalNumber = 0; int base = 1; int temp = n; while (temp) { int lastDigit = temp % 10; temp = temp/10; decimalNumber += lastDigit*base; base = base*2; } cout<<"Decimal form of "<<n<<" is "<<decimalNumber<<endl;; } int main() { DecimalToBinary(23); BinaryToDecimal(10101); return 0; }
출력
Binary form of 23 is 10111 Decimal form of 10101 is 21
위에 주어진 프로그램에는 DecimalToBinary와 BinaryToDecimal의 두 가지 함수가 있습니다. 이들은 각각 숫자를 10진수에서 2진수로, 2진수에서 10진수로 변환합니다.
DecimalToBinary 함수에서 10진수 n의 이진 값은 배열 binaryNumber[]에 저장됩니다. while 루프가 사용되며 루프의 각 반복에 대해 n 모듈러스 2 연산의 결과가 binaryNumber[]에 저장됩니다. 이것은 다음 코드 스니펫을 사용하여 표시됩니다.
while (n > 0) { binaryNumber[i] = n % 2; n = n / 2; i++; }
그런 다음 for 루프를 사용하여 이진수를 표시합니다. 이것은 다음과 같이 표시됩니다.
cout<<"Binary form of "<<num<<" is "; for (int j = i - 1; j >= 0; j--) cout << binaryNumber[j];
BinaryToDecimal() 함수에서 while 루프는 이진수를 십진수로 변환하는 데 사용됩니다. LastDigit은 임시 변수의 마지막 비트를 포함합니다. base는 2, 4, 6, 8 등과 같은 기본 값을 포함합니다. DecimalNumber는 이전 DecimalNumber 값과 LastDigit과 base의 곱의 합을 포함합니다.
이 모든 것은 다음 코드 스니펫을 사용하여 설명됩니다. -
while (temp) { int lastDigit = temp % 10; temp = temp/10; decimalNumber += lastDigit*base; base = base*2; }
main() 함수에서 DecimalToBinary() 및 BinaryToDecimal() 함수가 호출됩니다. 이것은 다음과 같이 표시됩니다.
DecimalToBinary(23); BinaryToDecimal(10101);