Trong hệ thống máy tính, số nhị phân dùng hệ cơ số 2, số thập phân dùng cơ số 10. Ví dụ chuyển đổi:
| Số thập phân | Số nhị phân |
|---|---|
| 15 | 1111 |
| 10 | 1010 |
| 18 | 10010 |
| 27 | 11011 |
Chương trình chuyển đổi thập phân sang nhị phân:
Ví dụ
#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 main() {
DecimalToBinary(15);
DecimalToBinary(10);
DecimalToBinary(18);
DecimalToBinary(27);
return 0;
}Đầu ra
Binary form of 15 is 1111 Binary form of 10 is 1010 Binary form of 18 is 10010 Binary form of 27 is 11011
Hàm DecimalToBinary lưu giá trị nhị phân vào mảng binaryNumber[]. Vòng lặp while lấy phần dư chia 2 lưu vào mảng.
while (n > 0) {
binaryNumber[i] = n % 2;
n = n / 2;
i++;
}Sau đó in ngược mảng để được số nhị phân đúng thứ tự.
cout << "Binary form of " << num << " is ";
for (int j = i - 1; j >= 0; j--)
cout << binaryNumber[j];