本文介绍了byte[] 到无符号 BigInteger?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

动机:我想将哈希(MD5/SHA1 等)转换为十进制整数,以便在 Code128C 中制作条形码.为简单起见,我希望所有结果(大)数字都是正数.

Motivation:I would like to convert hashes (MD5/SHA1 etc) into decimal integers for the purpose of making barcodes in Code128C.For simplicity, I prefer all the resulting (large) numbers to be positive.

我可以在 C# 中将 byte[] 转换为 BigInteger...
到目前为止我所拥有的样本:

I am able to convert byte[] to BigInteger in C#...
Sample from what I have so far:

byte[] data;
byte[] result;
BigInteger biResult;

result = shaM.ComputeHash(data);
biResult = new BigInteger(result);

但是(这里生疏的 CS)我是否正确,字节数组总是可以用两种方式解释:

But (rusty CS here) am I correct that a byte array can always be interpreted in two ways:

  • (A):作为有符号数
  • (B):作为无符号数

是否可以从 C# 中的 byte[] 生成 UNSIGNED BigInteger?

我应该在字节[]的前面简单地添加一个 0x00(零字节)吗?

Should I simply prepend a 0x00 (zero byte) to the front of the byte[]?

感谢 AakashM、Jon 和 Adam Robinson,附加一个零字节实现了我所需要的.

Thank you to AakashM, Jon and Adam Robinson, appending a zero byte achieved what I needed.

我应该做的主要事情是阅读 BigInteger(byte[]) 构造函数的详细文档,然后我就会看到有关如何通过附加零字节来限制为正数的部分.

The main thing I should have done was to read the detailed doc of the BigInteger(byte[]) constructor, then I would have seen the sections about how to restrict to positive numbers by appending the zero byte.

推荐答案

BigInteger 构造函数 的说明表明您可以确保任何BigIntegerbyte[]00 字节添加到数组末尾,则/code> 是无符号的.

The remarks for the BigInteger constructor state that you can make sure any BigInteger created from a byte[] is unsigned if you append a 00 byte to the end of the array before calling the constructor.

注意:BigInteger 构造函数期望数组采用小端顺序.如果您希望结果 BigInteger 具有特定值,请记住这一点.

Note: the BigInteger constructor expects the array to be in little-endian order. Keep that in mind if you expect the resulting BigInteger to have a particular value.

这篇关于byte[] 到无符号 BigInteger?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:27