Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การแสดงผลตัวเลขในรูปแบบไบนารีใน C++

ตัวเลขไบนารี (Binary Number)

ตัวเลขที่ประกอบด้วยเลข 0 และ 1 เท่านั้น เช่น 1101

วิธีที่ 1: ใช้ Recursion (เวียนเกิด)

หลักการ: หารตัวเลขด้วย 2 ซ้ำๆ เก็บเศษ แล้วพิมพ์จากล่างขึ้นบน

#include <iostream>
using namespace std;

void toBinary(unsigned n) {
    if (n > 1)
        toBinary(n / 2);
    cout << n % 2;
}

int main() {
    int n = 6;
    cout << n << " in binary: ";
    toBinary(n);
    cout << endl;
    
    n = 12;
    cout << n << " in binary: ";
    toBinary(n);
    return 0;
}

ผลลัพธ์: 6 → 110, 12 → 1100

วิธีที่ 2: ใช้ bitset (C++ STL)

#include <iostream>
#include <bitset>
using namespace std;

int main() {
    int n = 42;
    cout << bitset<8>(n) << endl;  // แสดง 8 บิต: 00101010
    cout << bitset<32>(n) << endl; // แสดง 32 บิต
    return 0;
}

วิธีที่ 3: ใช้ Bitwise Operations

#include <iostream>
using namespace std;

void printBinary(int n) {
    for (int i = 31; i >= 0; i--) {
        cout << ((n >> i) & 1);
        if (i % 4 == 0) cout << ' '; // จัดกลุ่ม 4 บิต
    }
    cout << endl;
}

int main() {
    printBinary(42); // 0000 0000 0000 0000 0000 0000 0010 1010
    return 0;
}

วิธีที่ 4: ใช้ std::format (C++20)

#include <iostream>
#include <format>
using namespace std;

int main() {
    int n = 42;
    cout << format("{:b}", n) << endl; // 101010
    return 0;
}