简体   繁体   English

java-如何生成一个6位随机十六进制值

[英]java- how to generate a 6 digit random hexadecimal value

I have a scenario in a Android app, where a random hexadecimal value has to be generated with 6 digits.我在 Android 应用程序中有一个场景,其中必须生成 6 位随机十六进制值。 (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?还是可以直接生成一个值?

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

You can use hex literals in your program the same way as decimal literals.您可以在程序中使用与十进制文字相同的方式使用十六进制文字。 A hex literal is prefixed with 0x .十六进制文字以0x为前缀。 Your max value is FFFFFF , so in your program you can write你的最大值是FFFFFF ,所以在你的程序中你可以写

int maxValue = 0xFFFFFF;

Then you need to generate random numbers in that range.然后您需要在该范围内生成随机数。 Use the Random class as you normally would.像往常一样使用Random类。

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

Note the use of maxValue + 1 , because the upper bound for nextInt() is exclusive.请注意maxValue + 1的使用,因为nextInt()的上限是独占的。

The final step is to print out your hex value.最后一步是打印出你的十六进制值。

System.out.printf("%06X", myValue);
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.这个随机对象使用 SecureRandom 类方法。 this class use for generate random number.这个类用于生成随机数。

     SecureRandom random = new SecureRandom();
  2. next int num object store 6 hexadecimal digit random number next int num 对象存储 6 个十六进制数字随机数

    int num = random.nextInt(0x1000000);
  3. then output num as 6 digit hexadecimal number然后将 num 输出为 6 位十六进制数

    String formatted = String.format("%06x", num);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM