java- how to generate a random hexadecimal value within specified range of values

decimal, hex, java

Solution

Yes, you just generate a decimal value in your range. Something such as:

Random rand = new Random();
int myRandomNumber = rand.nextInt(0x10) + 0x10; // Generates a random number between 0x10 and 0x20
System.out.printf("%x\n",myRandomNumber); // Prints it in hex, such as "0x14"
// or....
String result = Integer.toHexString(myRandomNumber); // Random hex number in result

Hex and decimal numbers are handled the same way in Java (as integers), and are just displayed or inputted differently. (More info on that.)

Problem

I have a scenario in a java web app, where a random hexadecimal value has to be generated. This value should be within a range of values specified by me. (The range of values can be hexadecimal or integer values). What is the most efficient way to do this> Do I have to generate a random decimal number, and then convert it to hexadecimal? Or can a value be directly generated?

Original source