
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Generate Random Hexadecimal Bytes in C++
We shall discuss about a C++ program which can generate random Hexadecimal numbers. Here we shall use rand() and itoa() functions to implement the same. Let us discuss on these functions separately and categorically.
rand(): rand() function is a predefined method of C++. It is declared in <stdlib.h> header file. rand() is used to generate random number within a range. Here min_n is the minimum range of the random numbers and max_n is the maximum range of the numbers. So rand() will return the random numbers between min_n to (max_n – 1) inclusive of the limit values. Here if we mention lower and upper limits as 1 and 100 respectively, then rand() will return values from 1 to (100 – 1). i.e. from 1 to 99.
itoa(): It returns the converted value of a decimal or integer number. It converts the value to a null-terminated string with a specified base. It stores the converted value to a user defined array.
Syntax
itoa(new_n, Hexadec_n, 16);
Here new_n is any random integer number and Hexadec_n is the user defined array and 16 is the base of hexadecimal number. That means in converts a decimal or integer number to hexadecimal number.
Algorithm
Begin Declare max_n to the integer datatype. Initialize max_n = 100. Declare min_n to the integer datatype. Initialize min_n = 1. Declare an array Hexadec_n to the character datatype. Declare new_n to the integer datatype. Declare i to the integer datatype. for (i = 0; i < 5; i++) new_n = ((rand() % (max_n + 1 - min_n)) + min_n) Print “The random number is:”. Print the value of new_n. Call itoa(new_n, Hexadec_n, 16) method to convert a random decimal number to hexadecimal number. Print “Equivalent Hex Byte:” Print the value of Hexadec_n. End.
Example
#include<iostream> #include<conio.h> #include<stdlib.h> using namespace std; int main(int argc, char **argv) { int max_n = 100; int min_n = 1; char Hexadec_n[100]; int new_n; int i; for (i = 0; i < 5; i++) { new_n = ((rand() % (max_n + 1 - min_n)) + min_n); //rand() returns random decimal number. cout<<"The random number is: "<<new_n; itoa(new_n, Hexadec_n, 16); //converts decimal number to Hexadecimal number. cout << "\nEquivalent Hex Byte: " <<Hexadec_n<<endl<<"\n"; } return 0; }
Output
The random number is: 42 Equivalent Hex Byte: 2a The random number is: 68 Equivalent Hex Byte: 44 The random number is: 35 Equivalent Hex Byte: 23 The random number is: 1 Equivalent Hex Byte: 1 The random number is: 70 Equivalent Hex Byte: 46