How to generate random hexadecimal strings in C++

In this tutorial, we are going to learn how to generate random hexadecimal strings in C++. Generating a hexadecimal number can be done using the rand() function of C++, which generates a random number. We can use this random number to find a random index of a string that contains all the hexadecimal characters. Let’s discuss it in detail.

Generate random hexadecimal strings in C++

To generate a random hexadecimal string, we are going to use the following functions.

  • rand(): This function is declared in stdlib.h header. This generates a random number. The syntax for rand() is as follows:
     int rand(void)
  • srand(): This function is also declared in stdlib.h header. This is most often used with rand() function to set the starting point for the generation of random integers. This has to be called only once for any number of calls of rand() function. We call this function with argument ‘time(0)’ to generate a different random number each time the rand() function is called. The syntax for srand() is as follows:
     void srand(unsigned int any_number)
  • time():¬†This function is declared in the header time.h and it returns the system time in seconds (seconds since JAN 1, 1970) when called with null or zero as an argument.
  • hex_string(): This is user-defined function. This function is used to generate a hexadecimal string using the rand() function. In this function, first, we store all the hexadecimal characters in a string. Then we use (rand() % 16) to generate a random number between 0 to 15 as an index for the string containing all the hexadecimal characters. We store character values at these indexes to the resultant string.

Here is a C++ program that illustrates very well how we can generate random hexadecimal strings. See the code below.

#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;

void hex_string(char str[], int length)
{
  //hexadecimal characters
  char hex_characters[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
  
  int i;
  for(i=0;i<length;i++)
  {
    str[i]=hex_characters[rand()%16];
  }
  str[length]=0;
}


int main()
{
  int n,length;
  char hex[30];
    cout<<"Enter number of random hexadecimal strings you want."<<endl;
    cin>>n;
    cout<<"Enter length of the hexadecimal strings."<<endl;
    cin>>length;
    srand(time(0));
    for(int i=0;i<n;i++)
    {
    	hex_string(hex,length);
        cout << "Hexadecimal String "<<i+1<<": " << hex<<endl;
  }
    return 0;
}

The output of the above program will be:

Enter number of random hexadecimal strings you want.
3
Enter length of the hexadecimal string.
7
Hexadecimal String 1: DC8C69D
Hexadecimal String 2: 8293736
Hexadecimal String 3: 9B846E2

Thank you.

Also read: How to create a random string in C++?

Leave a Reply

Your email address will not be published. Required fields are marked *