이 방법은 가장 기본적인 방법으로, 10진수를 2로 계속 나누면서 나머지를 저장한 후, 역순으로 출력하는 방식이다.
#include <iostream>
#include <string>
using namespace std;
string intToBinary(int num) {
if (num == 0) return "0";
string binary = "";
while (num > 0) {
binary.insert(0, to_string(num % 2));
num /= 2;
}
return binary;
}
int main() {
int num;
cout << "10진수를 입력하세요: ";
cin >> num;
cout << "2진수 변환 (2로 나누기): " << intToBinary(num) << endl;
return 0;
}
10을 변환하는 과정:
1. 10 ÷ 2 = 5, 나머지 0
2. 5 ÷ 2 = 2, 나머지 1
3. 2 ÷ 2 = 1, 나머지 0
4. 1 ÷ 2 = 0, 나머지 1
insert로 숫자를 계속 맨 앞에 추가해서 1010이 된다.
insert(0, ...) 연산으로 인해 속도가 느릴 수 있음 비트 연산을 활용하면 더 간결하게 2진수를 출력할 수 있다. 이 방법은 정수를 오른쪽으로 시프트(>>)하면서 최하위 비트를 확인하는 방식dl다.
#include <iostream>
#include <string>
using namespace std;
string intToBinary(int num) {
if (num == 0) return "0";
string binary = "";
for (int i = 31; i >= 0; i--) {
binary += ((num >> i) & 1) ? '1' : '0';
}
binary.erase(0, binary.find_first_not_of('0'));
return binary;
}
int main() {
int num;
cout << "10진수를 입력하세요: ";
cin >> num;
cout << "2진수 변환 (시프트 연산): " << intToBinary(num) << endl;
return 0;
}
10(1010)을 변환하는 과정:
1. 10 >> 31 → 최상위 비트 확인 (0)
2. 10 >> 30 → 최상위 비트 확인 (0)
3. …
4. 10 >> 3 → 1
5. 10 >> 2 → 0
6. 10 >> 1 → 1
7. 10 >> 0 → 0
32비트 형태로 출력되는데 erase 함수로 leadingZero 처리해서 1010이 출력된다.
bitset을 활용하는 방법<bitset> 라이브러리를 활용하면 가장 간단하게 변환할 수 있다.
#include <iostream>
#include <bitset>
#include <string>
using namespace std;
string intToBinary(int num) {
bitset<32> bs(num);
string binary = bs.to_string();
binary.erase(0, binary.find_first_not_of('0'));
return binary;
}
int main() {
int num;
cout << "10진수를 입력하세요: ";
cin >> num;
cout << "2진수 변환 (bitset): " << intToBinary(num) << endl;
return 0;
}
bitset을 사용하면 간결한 코드로 변환 가능 .to_string()을 사용해 문자열로 변환하여 활용 가능 bitset<32>로 고정되어 있어, 64비트 정수의 경우 bitset<64>로 수정 필요