เลขฐานสอง เป็นตัวเลขที่ประกอบด้วยตัวเลขสองหลักเท่านั้น 0 และ 1 เช่น 01010111
มีหลายวิธีในการแสดงตัวเลขที่กำหนดในรูปแบบไบนารี
วิธีการแบบเรียกซ้ำ
วิธีนี้ใช้แทนตัวเลขในรูปแบบไบนารีโดยใช้การเรียกซ้ำ
อัลกอริทึม
Step 1 : if number > 1. Follow step 2 and 3. Step 2 : push the number to a stand. Step 3 : call function recursively with number/2 Step 4 : pop number from stack and print remainder by dividing it by 2.
ตัวอย่าง
#include<iostream>
using namespace std;
void tobinary(unsigned number){
if (number > 1)
tobinary(number/2);
cout << number % 2;
}
int main(){
int n = 6;
cout<<"The number is "<<n<<" and its binary representation is ";
tobinary(n);
n = 12;
cout<<"\nThe number is "<<n<<" and its binary representation is ";
tobinary(n);
} ผลลัพธ์
The number is 6 and its binary representation is 110 The number is 12 and its binary representation is 1100