生成具有指定位长的随机数?

Pri*_*lly 1 java random android bit-manipulation bit

我正在尝试制作一个可以生成随机数并指定随机数可以是多少位的函数。

更具体地说,我正在尝试生成一个长度为 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
    }
}
Run Code Online (Sandbox Code Playgroud)

rzw*_*oot 5

创建一个 的新实例java.util.Random,最好只为您的整个应用程序创建一个。

然后,您可以调用.nextInt(x)它,其中 x 是上限(不包括)。所以,如果你想要一个 4 位随机数,你会调用.nextInt(16),或者如果你发现它更易读(它变成完全相同的字节码).nextInt(0x10),它会生成一个介于 0(含)和 16(不含)之间的随机数,所以,从00001111

要找到“16”,只需1 << (bits-1). 例如rnd.nextInt(1 << (12-1))会给你一个 12 位的随机数。

数字只是。Anint没有十六进制、十进制或二进制的概念。这是您在打印时选择的内容。String.format("%x", 10)将打印A例如。