Skip to content
Related Articles

Related Articles

Java Program to Generate Random Hexadecimal Bytes
  • Last Updated : 02 Dec, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output

Random Hexadecimal Byte: 61fdc065

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :