【发布时间】:2020-10-16 01:55:36
【问题描述】:
我正在尝试制作一个可以生成随机数并指定随机数可以是多少位的函数。
更具体地说,我正在尝试生成一个 8、10 或 12 位长的数字。这个位数由另一个变量指定。
然后我想将此数字表示为字符串中的十六进制或十进制中的有符号和无符号整数。我想我可以在这部分使用各种 Integer.toString 方法。
如何在 Java 中生成特定位长的随机数?
到目前为止,我已经有了这个功能框架:
public static String generateQuestion(int numBits, int taskType){
String questionStr = "";
String questionVal = ""; // This is the string hexadecimal version of the randomly generated number
// TODO: Code to generate random value based on numBits
switch(taskType){
case 0: // Hex to Decimal
questionStr = "What are the signed and unsigned values for the " + numBits + "-bit value " + questionVal + "?";
return questionStr; // Return the constructed string
case 1: // Signed Decimal to Hex
case 2: // Unsigned Decimal to Hex
default:
throw new IllegalStateException("Unexpected Question Type: " + taskType); // In case the task type is something other than the 3 possible question types
}
}
【问题讨论】:
-
您需要加密安全的号码还是仅仅需要良好的分布?
-
我不需要安全号码。我只需要一些非常简单的东西,它有一个不错的范围和随机性。至于链接,我在发布之前看到了它,但我认为它不涉及我的特定位要求。它生成一个范围内的数字,但我不知道如何设置范围以匹配位长。
-
也许可以为每个指定的位长度创建一个max_var?
-
要生成一个8位的数,用2^8, 10, 2^10, 12, 2^12,这不就是字面上的定义吗?
-
嗯,可以。我想知道这是否仅适用于 base-10,但我可以将其生成为十进制并稍后转换为十六进制。
标签: java android random bit-manipulation bit