โจทย์
แปลงเลขฐานสิบ (Decimal) เป็นฐานสอง (Binary) โดยใช้ฟังก์ชัน
ตรรกะ
while (dno != 0) {
rem = dno % 2;
bno = bno + rem * f;
f = f * 10;
dno = dno / 2;
}
โปรแกรม Decimal to Binary
#include <stdio.h>
long tobinary(int);
int main() {
long bno;
int dno;
printf("Enter any decimal number: ");
scanf("%d", &dno);
bno = tobinary(dno);
printf("The Binary value is: %ld\n", bno);
return 0;
}
long tobinary(int dno) {
long bno = 0, rem, f = 1;
while (dno != 0) {
rem = dno % 2;
bno = bno + rem * f;
f = f * 10;
dno = dno / 2;
}
return bno;
}
ผลลัพธ์
Enter any decimal number: 12
The Binary value is: 1100
โปรแกรม Binary to Decimal (เพิ่มเติม)
#include <stdio.h>
#include <math.h>
int todecimal(long bno);
int main() {
long bno;
int dno;
printf("Enter a binary number: ");
scanf("%ld", &bno);
dno = todecimal(bno);
printf("The decimal value is: %d\n", dno);
return 0;
}
int todecimal(long bno) {
int dno = 0, i = 0, rem;
while (bno != 0) {
rem = bno % 10;
bno /= 10;
dno += rem * pow(2, i);
++i;
}
return dno;
}
ผลลัพธ์
Enter a binary number: 10011
The decimal value is: 19