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

โปรแกรม C++ แปลงเลขฐานสิบ (Decimal) เป็นฐานสิบหก (Hexadecimal)


บทนำ

แปลงเลขฐานสิบ (Base 10) เป็นฐานสิบหก (Base 16) โดยใช้ A-F แทน 10-15

ขั้นตอน

  1. หารตัวเลขด้วย 16 เก็บเศษ (0-9 เก็บไว้, 10-15 แปลงเป็น A-F)
  2. หารผลหารด้วย 16 ซ้ำจนกว่าจะหารไม่ลง
  3. อ่านเศษจากล่างขึ้นบน (reverse)

ตัวอย่าง

6789 ÷ 16 = 424 เศษ 5 → 424 ÷ 16 = 26 เศษ 8 → 26 ÷ 16 = 1 เศษ 10(A) → 1 ÷ 16 = 0 เศษ 1 → ผลลัพธ์: 1A85

ตัวอย่างโค้ด C++

#include <iostream>
using namespace std;

void convert(int num) {
    char arr[100];
    int i = 0;
    while (num != 0) {
        int temp = num % 16;
        if (temp < 10)
            arr[i++] = temp + 48;  // '0' = 48
        else
            arr[i++] = temp + 55;  // 'A' = 65
        num /= 16;
    }
    for (int j = i - 1; j >= 0; j--)
        cout << arr[j];
}

int main() {
    int num = 6789;
    cout << num << " converted to hexadecimal: ";
    convert(num);
    return 0;
}

ผลลัพธ์

6789 converted to hexadecimal: 1A85