This question already has answers here:
How to generate a random BigInteger value in Java?
(8 answers)
Closed 2 years ago.
I am attempting to generate a random 20 digit BigInteger in Java.
So far, I have been able to generate a fixed length hex value.
// generate a user-specified number of random bytes
public void getRandomNumber(int count) {
byte[] bytes = new byte[count];
new SecureRandom().nextBytes(bytes);
String random = new String(Hex.encode(bytes));
System.out.println(random);
}
This is ideal for a fixed length hex generation. But I struggle to find an efficient method of doing this for a decimal representation; when converting from hex to BigInteger(hexValue, 16), the length will vary.
I have considered trying this by setting upper and lower bounds, or by generating something big enough and trimming to the desired length, but those methods do not feel very clean.
Edit: The solution I have came up with that is working fine in my program:
// generate a random number with specified bit length
public void getTokenID() {
int count = 64;
SecureRandom rnd = new SecureRandom();
BigInteger randomCountLength;
String token;
do {
randomCountLength = new BigInteger(count, rnd);
token = randomCountLength.toString();
} while (token.length() != 20);
Tid = token;
}
What I understand that your problem is to generate random number with fixed length (fixed number of digits)
It is obvious that using hex value will work since any hex digit represent 4 bytes. So when you fix the length of bytes (bytes table in your code) it work fine
What I advice you when dealing with decimal number is :
1- There is methods for generating random number with lower and upper bound, for example Random betwen 5 and 10, so if you want for example a random number with 20 digits , you have to generate random number between (10^19) and (10^20-1)
2- The second is hardcoded method to make a loop of 20 iterations when you generate random digit (between 0 and 9 exept the the digit of strong weight which must be between 1 and 9) and you get the number.
Related
This question already has answers here:
Integer to two digits hex in Java
(7 answers)
Closed 1 year ago.
I'm trying to pad a hexadecimal digit with 0's in the beginning so that the length of it is always 4. For example, the FF is going to be padded as 00FF. I have tried to use String.format("%04d", number) but it didn't work as my hexadecimal digit is actually a string.
I have also tried using StringUtils.leftPad() but for some reason, IntelliJ couldn't detect it.
Please note my count is going to change, but I haven't represented it here as I'm yet to implement it. This is my sample code. Thanks.
public static void main(String[] args) {
int count = 0;
String orderID = Integer.toHexString(count).toUpperCase();
System.out.println(String.format("%04d", Integer.valueOf(orderID)));
}
String.format("%04x", 255)
with output
00ff
(or use X for uppercases hex digits)
As #user16320675 point, more info about Formatter here.
I am trying to generate two 9 digit long random long value in Java using the below code:
for (int i =0;i<2;i++) {
String axisIdStr = Long.toString((long)(System.nanoTime() * (Math.random() * 1000)));
System.out.println("######## axisIdStr "+axisIdStr);
String axId = axisIdStr.substring((axisIdStr.length() -9), axisIdStr.length()) ;
}
But when I run this in windows, i get two different numbers where as when run in mac, I get same two numbers. Why is this happening ?
Can you suggest a better way to generate the long values?
According to your requirement you need to generate 9 digit random numbers. As in the comment suggested you can do it using random.Below I have just given one solution to generate random number between two numbers.
long lowerLimit = 123456712L;
long upperLimit = 234567892L;
Random r = new Random();
long number = lowerLimit+((long)(r.nextDouble()*(upperLimit-lowerLimit)));
You could create an array a[] of int of size 9, and populate with random integers 0-9. Then sum the array up multiplying accordingly.
a[8]*1 + a[7]*10 + a[6]*100 ...
You need to make sure that a[0] only takes digits 1-9 tho...
To get even more random sequence, you Ideally should work on Strings, then you would be able to get 0 on the start position of your random "string", it won't be a number.
Or maybe generate somthing pseudo random and strip last 9 digits out of it.
That's the DIY version of what you could accomplish with what's already out there...
Regards
I want to create a randomly generated 16 digit-number in java.But there is a catch I need the first two digits to be "52". For example, 5289-7894-2435-1967.
I was thinking of using a random generator and create a 14 digit number and then add an integer 5200 0000 0000 0000.
I tried looking for similar problems and can't really find something useful. I'm not familiar with the math method,maybe it could solve the problem for me.
First, you need to generate a random 14-digit number, like you've done:
long first14 = (long) (Math.random() * 100000000000000L);
Then you add the 52 at the beginning.
long number = 5200000000000000L + first14;
One other way that would work equally well, and will save memory, since Math.random() creates an internal Random object:
//Declare this before you need to use it
java.util.Random rng = new java.util.Random(); //Provide a seed if you want the same ones every time
...
//Then, when you need a number:
long first14 = (rng.nextLong() % 100000000000000L) + 5200000000000000L;
//Or, to mimic the Math.random() option
long first14 = (rng.nextDouble() * 100000000000000L) + 5200000000000000L;
Note that nextLong() % n will not provide a perfectly random distribution, unlike Math.random(). However, if you're just generating test data and it doesn't have to be cryptographically secure, it works as well. It's up to you which one to use.
Random rand = new Random();
String yourValue = String.format((Locale)null, //don't want any thousand separators
"52%02d-%04d-%04d-%04d",
rand.nextInt(100),
rand.nextInt(10000),
rand.nextInt(10000),
rand.nextInt(10000));
You can generate 14 random digits and then append at the beginning "52". E.g.
public class Tes {
public static void main(String[] args) {
System.out.println(generateRandom(52));
}
public static long generateRandom(int prefix) {
Random rand = new Random();
long x = (long)(rand.nextDouble()*100000000000000L);
String s = String.valueOf(prefix) + String.format("%014d", x);
return Long.valueOf(s);
}
}
Create a 14 random digit number. with Math.random
Concatenate to it at the begining the "52" String.
Convert the string with Integer.parseInt(String) method
I want to create randomally number with 16 digits in java.
I can do it with String and after that convert to Long.
there is other option?
Thanks!
You can use the Java class Random to generate random Longs, like here for numbers up to one million:
final long MAX_NUMBER_YOU_WANT_TO_HAVE = 9999999999999999L;
final long MIN_NUMBER_YOU_WANT_TO_HAVE = 1000000000000000L;
Long actual = Long.valueOf(Math.abs(Float.valueOf(new Random().nextFloat() * (MAX_NUMBER_YOU_WANT_TO_HAVE - MIN_NUMBER_YOU_WANT_TO_HAVE)).longValue()));
If you absolutely need 16 digits (not a number from 0 to 10^17-1)
Random rand = new Random;
long accumulator = 1 + rand.nextInt(9); // ensures that the 16th digit isn't 0
for(int i = 0; i < 15; i++) {
accumulator *= 10L;
accumulator += rand.nextint(10);
}
I might have an off-by-one on the for loop, use i < 16 if need be.
Your reason for wanting 16 digits is probably key here.
If you only want a number possibly as big as the biggest 16-digit number, then use your favored random number generator to generate a random number between 0 and 9 999 999 999 999 999. You can then add leading zeroes as needed to display exactly 16 characters if that's the reason.
If you explicitly want there to be 16 decimal digits and the first one cannot be zero, you can try the same exercise with 999 999 999 999 999 as upper bound instead and add a random digit from 1 to 9 in front (multiply it by a quadrillion and then sum with the other random number, if need be).
There's plenty of other options, but those are probably the most obvious and simple to implement. I'm quite sure there are native facilities in Java for generating random long numbers.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Java: generating random number in a range
I want to generate a random int in a logical range. So, say for example, I'm writing a program to "roll" a dice with a specified number of sides.
public int rollDice() {
Random generator = new Random();
return generator.nextInt(sides);
}
Now the problem becomes that this will return values between sides and zero, inclusive, which makes no sense because most dice go from 1 to 6, 9, etc. So how can I specify that nextInt should work between 1 and the number of sides?
To generate a random int value (uniform distribution) between from and to (inclusive) use:
from + rndGenerator.nextInt(to - from + 1)
In your case (1..sides):
1 + rndGenerator.nextInt(sides)