To generate Random Hexadecimal Bytes, first, a random byte can be generated in decimal form using Java.util.Random.nextInt() and then it can be converted to hexadecimal form using Integer.toHexString() method.
1. Java.util.Random.nextInt()
The nextInt() method is used to obtain the next integer from this random number generator’s sequence. Here the range can also be specified which will return a number between 0 inclusive and the specified number exclusive.
Declaration
public int nextInt()
Return Value: The method call returns the next integer number from the random number generator sequence
Example:
// Here printing n is a random integer. int n = ran.nextInt();
2. Integer.toHexString()
toHexString() is a built-in method in Java which returns a string representation of the integer argument as an unsigned integer in base 16. The function takes a single parameter as an argument in Integer data-type.
Declaration
public static String toHexString(int num)
Return value: It returns string representation of the integer argument as an unsigned int in base 16
Example:
Input:13 Output:d Input:14 Output:e
Example
Java
// Java Program to Generate Random Hexadecimal Bytes import java.io.*; import java.util.Random; class GFG { public static void main(String[] args) { // Random instance Random r = new Random(); int n = r.nextInt(); // n stores the random integer in defcimal form String Hexadecimal = Integer.toHexString(n); // toHexString(n) converts n to hexadecimal form System.out.println( "Random Hexadecimal Byte: " + Hexadecimal); } } |
Random Hexadecimal Byte: 61fdc065