Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

decimal

hex

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?

like image 949
Arvind Avatar asked Jun 19 '12 05:06

Arvind


People also ask

How do you generate a random hexadecimal in Java?

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.

How do you use hexadecimal numbers in Java?

In Java code (as in many programming languages), hexadecimal nubmers are written by placing 0x before them. For example, 0x100 means 'the hexadecimal number 100' (=256 in decimal).

What is hexadecimal code?

Hexadecimal is a numbering system with base 16. It can be used to represent large numbers with fewer digits. In this system there are 16 symbols or possible digit values from 0 to 9, followed by six alphabetic characters -- A, B, C, D, E and F.


1 Answers

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.)

like image 174
Cat Avatar answered Sep 20 '22 16:09

Cat