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

Chương trình C++ sinh byte hex ngẫu nhiên

Chương trình sinh số ngẫu nhiên trong khoảng [1, 100] và chuyển đổi sang dạng hexadecimal (cơ số 16) bằng hàm itoa() (Windows) hoặc sprintf (portable).

Hàm itoa() (Windows-specific)


char* itoa(int value, char* str, int base);
// value: số cần chuyển
// str: buffer nhận kết quả
// base: cơ số (2, 8, 10, 16...)

Ví dụ: Sinh 5 số hex ngẫu nhiên


#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {
    int max_n = 100;
    int min_n = 1;
    char hex_str[100];
    int num;
    
    srand(time(nullptr));
    
    for (int i = 0; i < 5; ++i) {
        num = min_n + rand() % (max_n - min_n + 1);  // [1, 100]
        cout << "So ngau nhien: " << num;
        
        // Chuyển sang hex
        // itoa(num, hex_str, 16);  // Windows only
        sprintf(hex_str, "%x", num);  // Portable (C/C++)
        
        cout << " -> Hex: " << hex_str << endl;
    }
}

Kết quả mẫu

So ngau nhien: 42 -> Hex: 2a
So ngau nhien: 68 -> Hex: 44
So ngau nhien: 35 -> Hex: 23
So ngau nhien: 1 -> Hex: 1
So ngau nhien: 70 -> Hex: 46

Cách hiện đại C++11: std::format / iomanip


#include <iostream>
#include <random>
#include <iomanip>

int main() {
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> dist(1, 100);
    
    for (int i = 0; i < 5; ++i) {
        int num = dist(gen);
        cout << "Dec: " << num 
             << " Hex: " << hex << uppercase << num 
             << nouppercase << dec << endl;
    }
}

Kết quả

Dec: 42 Hex: 2A
Dec: 68 Hex: 44
Dec: 35 Hex: 23
Dec: 1 Hex: 1
Dec: 70 Hex: 46

Sinh byte hex ngẫu nhiên (0-255) cho crypto/data


#include <iostream>
#include <random>
#include <iomanip>
#include <vector>

int main() {
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> dist(0, 255);
    
    vector<unsigned char> bytes(16);
    for (auto& b : bytes) b = static_cast<unsigned char>(dist(gen));
    
    cout << "Random bytes: ";
    for (auto b : bytes) {
        cout << hex << setw(2) << setfill('0') << static_cast<int>(b) << ' ';
    }
    cout << dec << endl;
}

Kết quả

Random bytes: a3 7f 12 00 ff 4b 89 23 e1 05 77 9a bc d4 33 11

Tóm tắt

  • itoa(): Windows-only, không chuẩn C++
  • sprintf(buf, "%x", n): Portable C
  • C++ iostream: cout << hex << n (dễ dùng)
  • C++20: std::format("{:02x}", n)
  • Dùng <random> thay rand() cho chất lượng tốt hơn