Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Convert a Number to Hexadecimal trong C++


Chuyển số nguyên sang hệ thập lục phân (hex). Với số âm dùng bù 2 (two's complement).

Ví dụ: 254 → "fe", -12 → "ffffff4" (32-bit).

Giải thuật

  1. Nếu num == 0 trả về "0".
  2. Ép kiểu sang unsigned int (để xử lý bù 2 tự động).
  3. Lặp chia 16, lấy phần dư, chuyển sang ký tự hex (0-9, a-f).
  4. Đảo ngược chuỗi kết quả.

Ví dụ triển khai C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    string toHex(int num) {
        if (num == 0) return "0";
        unsigned int n = num;
        string hex;
        while (n) {
            int d = n % 16;
            hex.push_back(d < 10 ? '0' + d : 'a' + d - 10);
            n /= 16;
        }
        reverse(hex.begin(), hex.end());
        return hex;
    }
};

int main() {
    Solution ob;
    cout << ob.toHex(254) << endl;  // fe
    cout << ob.toHex(-12) << endl; // fffffff4
    return 0;
}

Đầu vào / Đầu ra

Input: 254, -12
Output: fe, fffffff4