How to generate a random hexadecimal string in C++

1 Answer

0 votes
#include <iostream>
#include <cstdlib>
#include <ctime>

std::string generateHex(int length) {
    const char hexChars[] = "0123456789ABCDEF";
    std::string hexStr;

    for (int i = 0; i < length; ++i) {
        hexStr += hexChars[rand() % 16];
    }

    return hexStr;
}

int main() {
    srand(static_cast<unsigned int>(time(0))); // Seed the random number generator

    int length = 8; // Length of the hex string
    std::string hexNumber = generateHex(length);

    std::cout << "Random Hexadecimal Number: " << hexNumber << std::endl;
}

  
  
/*
run:
  
Random Hexadecimal Number: 642F0AC0
  
*/

 



answered Sep 16, 2025 by avibootz

Related questions

1 answer 125 views
2 answers 385 views
1 answer 170 views
1 answer 162 views
...