-1

I'm attempting to implement a random number generator system; essentially I'm reading in an SHA1 hash, which then gets converted into a BigInteger value:

String start = "abc";
String hash = utils.SHA1(start); //Generates an SHA1 hash of the string
byte[] bytes = hash.getBytes();
BigInteger big = new BigInteger(bytes);

This code generates a BigInteger with a value of:

811203900027758629330492243480887228261034167773619203962320290854945165232584286910163772258660

What I need to somehow do (and this is where I get confused), is reduce that number into a much shorter number with a fixed number of decimal places.

Using a combination of modular arithmetic and Java Math API functions, is there a sensible way of reducing this number down into a 3 digit number. Or any other length of number I choose.

At the moment I'm just simply converting that huge number into a String, and then taking a substring of the length of number I want. However I'm not entirely happy with this as the numbers I get aren't that random, as the range is somewhat limited with 3 digits.

The whole purpose of this is for the newly generated random x digit number to be then converted into a string using a radix of 36, to also include ASCII alphabet characters.

Any information or advice would be greatly appreciated.

Thanks!!

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
Tony
  • 3,587
  • 8
  • 44
  • 77
  • 3
    So you want 3 digits but you don't want 3 digits because they're limited? I don't understand... – m0skit0 Feb 23 '12 at 12:39
  • He want's x digits - depending on the situation... – DaveFar Feb 23 '12 at 12:46
  • That integer is the ASCII hex representation of the hash value, `a9993e364706816aba3e25717850c26c9cd0d89d`, so it is twice as large as needed. Googling the above reveals that it is the hash of ... well, you can google it yourself. – President James K. Polk Feb 23 '12 at 12:57

1 Answers1

1

Yes you can use modulus like .mod(1000) or for base 36 .mod(36*36*36) or even plain .longValue() % 1000 or .longValue() % (36*36*36)

You can use Long.toString(x, 10) or Long.toString(x, 36)

Not sure I can tell much more without giving you the answer.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Thanks Peter, that's just what I needed!! – Tony Feb 23 '12 at 13:07
  • Note: this is not the complete answer, but should point you in the right direction. – Peter Lawrey Feb 23 '12 at 13:10
  • It did yes thankyou. I just wanted some pointers on modular manipulation of huge numbers, and that's what you gave me. I never asked for the full answer anyway, just advice :) Thanks dude. – Tony Feb 23 '12 at 13:28
  • As the whole number should be equally random, you can use any portion of it. e.g. the first three digits are just as good as the last three. There's lots of ways you could do it, so I would stick with the simplest. – Peter Lawrey Feb 23 '12 at 13:31