2

I have a scenario in a Android app, where a random hexadecimal value has to be generated with 6 digits. (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?

kavie
  • 2,154
  • 4
  • 28
  • 53
  • 7
    Numbers are numbers. Just generate them within the needed range and do the conversion when you display them. – Federico klez Culloca Jun 18 '18 at 07:31
  • Possible duplicate of [this](https://stackoverflow.com/questions/11094823/java-how-to-generate-a-random-hexadecimal-value-within-specified-range-of-value) – Grenther Jun 18 '18 at 07:35
  • 1
    Combine [How do I generate random integers within a specific range in Java?](https://stackoverflow.com/q/363681) with `Integer.toHexString(int)` – Pshemo Jun 18 '18 at 07:35
  • 1
    6 digit hexademical number is 3 bytes. 3 bytes is 0..16777215 integer. Just generate integer in that range, and then show it as hex. – Vladyslav Matviienko Jun 18 '18 at 07:38
  • Random rnd = new Random(); int n = rnd.nextInt(999999); Integer.valueOf(String.valueOf(n), 16); – Eugen Jun 18 '18 at 07:38

4 Answers4

9
    String zeros = "000000";
    Random rnd = new Random();
    String s = Integer.toString(rnd.nextInt(0X1000000), 16);
    s = zeros.substring(s.length()) + s;
    System.out.println("s = " + s);
gagan singh
  • 1,591
  • 1
  • 7
  • 12
6

You can use hex literals in your program the same way as decimal literals. A hex literal is prefixed with 0x. Your max value is FFFFFF, so in your program you can write

int maxValue = 0xFFFFFF;

Then you need to generate random numbers in that range. Use the Random class as you normally would.

Random r = new Random();
int myValue = r.nextInt(maxValue + 1);

Note the use of maxValue + 1, because the upper bound for nextInt() is exclusive.

The final step is to print out your hex value.

System.out.printf("%06X", myValue);
Sam
  • 8,330
  • 2
  • 26
  • 51
4
SecureRandom random = new SecureRandom();
int num = random.nextInt(0x1000000);
String formatted = String.format("%06x", num); 
System.out.println(formatted);

Code Explain

  1. this random object use SecureRandom Class method. this class use for generate random number.

    SecureRandom random = new SecureRandom();
    
  2. next int num object store 6 hexadecimal digit random number

    int num = random.nextInt(0x1000000);
    
  3. then output num as 6 digit hexadecimal number

    String formatted = String.format("%06x", num); 
    
Erhannis
  • 4,256
  • 4
  • 34
  • 48
Ravi Patel
  • 309
  • 2
  • 13
1

More generally:

int digits = 6;
String hex = String.format("%0" + digits + "x", new BigInteger(digits * 4, new SecureRandom()));
Jesse Glick
  • 24,539
  • 10
  • 90
  • 112