java-如何在指定的值范围内生成一个随机的十六进制值 [英] java- how to generate a random hexadecimal value within specified range of values

查看:148
本文介绍了java-如何在指定的值范围内生成一个随机的十六进制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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-如何在指定的值范围内生成一个随机的十六进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆