将 Java BigInteger 减少为固定长度的较小数字

发布于 2025-01-08 14:44:10 字数 743 浏览 2 评论 0原文

我正在尝试实现一个随机数生成器系统;本质上,我正在读取 SHA1 哈希,然后将其转换为 BigInteger 值:

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

此代码生成一个 BigInteger,其值为:

811203900027758629330492243480887228261034167773619203962320290854945165232584286910163772258660

我需要以某种方式做的事情(这就是我感到困惑的地方),是将数字减少为一个短得多的数字,具有固定的小数位数。

结合使用模算术和 Java Math API 函数,是否有一种明智的方法可以将此数字减少为 3 位数字。或者我选择的任何其他长度的数字。

目前,我只是简单地将这个巨大的数字转换为字符串,然后获取我想要的数字长度的子字符串。然而我对此并不完全满意,因为我得到的数字不是那么随机,因为范围有点限制在 3 位数字。

这样做的全部目的是为了将新生成的随机 x 位数字转换为基数为 36 的字符串,其中还包括 ASCII 字母字符。

任何信息或建议将不胜感激。

谢谢!!

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!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦醒灬来后我 2025-01-15 14:44:10

是的,您可以使用模数,如 .mod(1000) 或基数 36 .mod(36*36*36) 甚至简单的 .longValue() % 1000.longValue() % (36*36*36)

您可以使用 Long.toString(x, 10)Long.toString(x, 36)

不确定我能否在不给您答案的情况下告诉您更多信息。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文