I'm trying to make a function that can generate a random number and specify how many bits the random number can be.
More specifically, I am trying to generate a number that could either be 8, 10, or 12 bits long. This bit amount is specified by another variable.
I then want to represent this number as a hex in string or as an signed and unsigned integer in decimal. I think i can just use the various Integer.toString methods for that part.
How would I go about generating specific bit-length random numbers in Java?
So far, I have this function skeleton in place:
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
}
}
Make a new instance of java.util.Random
, preferably only one for your entire app.
Then, you can invoke .nextInt(x)
on it, where x is the upper bound (exclusive). So, if you want a 4 bit random number, you'd call .nextInt(16)
, or if you find it more readable (it turns into the exact same bytecode), .nextInt(0x10)
, which generates a random number between 0 (inclusive) and 16 (exclusive), so, from 0000
to 1111
.
To find the '16', it's just 1 << (bits-1)
. e.g. rnd.nextInt(1 << (12-1))
will give you a 12 bit random number.
Numbers just are. An int
has no notion of hex or decimal or binary. That's a thing you choose when you print it. String.format("%x", 10)
will print A
for example.