byte[] to unsigned BigInteger?

gus picture gus · Apr 13, 2011 · Viewed 12.9k times · Source

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.

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);

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

  • (A): as a signed number
  • (B): as an unsigned number

Is it possible to make an UNSIGNED BigInteger from a byte[] in C#?

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

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

EDIT2: 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.

Answer

Jon picture Jon · Apr 13, 2011

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.

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.