Hi, I am

Ngô Tôn

I am a programmer.

Home / Programming / C/C++ / Đổi từ hệ thập phân sang nhị phân

Đổi từ hệ thập phân sang nhị phân

Yêu cầu:

Convert số từ hệ thập phân sang nhị phân.

Ví dụ: 15 (hệ thập phân) = 1111 (hệ nhị phân)

Thuật toán:

Lấy số hệ thập phân chia cho 2 để tìm phần dư. Phép toán này được thực hiện liên tục tới khi nào phép chia bằng 0.

Code:

#include "stdio.h"
#include "conio.h"

void main()
{
unsigned long num, binary_val = 0, decimal_val, base = 1, rem;

printf("\nNhap so nguyen he thap phan: ");
scanf("%ld", &num); /* maximum five digits */
decimal_val = num;
while (num > 0)
{
rem = num % 2;
binary_val = binary_val + rem * base;
num = num / 2;
base = base * 10;
}
printf("So thap phan = %d \n", decimal_val);
printf("So nhi phan = %d \n", binary_val);
getch();
}

Kết quả:

About ngoton

Ngô Tôn is a programmer with passion for tailored software solutions. Comes with 7+ years of IT experience, to execute beautiful front-end experiences with secure and robust back-end solutions.

Check Also

Xây dựng hàm bạn để tính diện tích hình chữ nhật

Yêu cầu: Xây dựng hàm bạn để tính diện tích hình chữ nhật Code: Giải …

Leave a Reply

avatar
  Subscribe  
Notify of