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:
/************************************************************ * Author: VNCODING * History * 2015/11/02 first create VNCODING *************************************************************/ #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ả:
Nhap so nguyen he thap phan: 257 So thap phan = 257 So nhi phan = 100000001
Leave a Reply
You must be logged in to post a comment.