byte[] to unsigned BigInteger?

后端 未结 6 782
逝去的感伤
逝去的感伤 2020-12-06 09:21

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 al

6条回答
  •  粉色の甜心
    2020-12-06 09:54

    As other answers have pointed out, you should append a 00 byte to the end of the array to ensure the resulting BigInteger is positive.

    According to the the BigInteger Structure (System.Numerics) MSDN Documentation

    To prevent the BigInteger(Byte[]) constructor from confusing the two's complement representation of a negative value with the sign and magnitude representation of a positive value, positive values in which the most significant bit of the last byte in the byte array would ordinarily be set should include an additional byte whose value is 0.

    Here's code to do it:

    byte[] byteArray;
    // ...
    var bigInteger = new BigInteger(byteArray.Concat(new byte[] { 0 }).ToArray());
    

提交回复
热议问题