问题描述
我在java web应用程序中有一个场景,其中必须生成一个随机的十六进制值。这个值应该在我指定的值范围内。 (值的范围可以是十六进制或整数值)。
执行此操作的最有效方法是>必须生成一个随机十进制数,然后将其转换为十六进制?或者可以直接生成一个值?
是的,您只需在您的范围内生成一个十进制值。例如:
随机rand = new Random();
int myRandomNumber = rand.nextInt(0x10)+ 0x10; //产生一个介于0x10和0x20之间的随机数
System.out.printf(%x \ n,myRandomNumber); //以十六进制打印,如0x14
//或....
字符串结果= Integer.toHexString(myRandomNumber); //结果中的随机十六进制数
十六进制和十进制数在Java中以相同的方式处理),只是显示或输入不同。 (的更多信息。)
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?
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.)
这篇关于java-如何在指定的值范围内生成一个随机的十六进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!