开发者

Shift a 128-bit signed BigInteger to always be positive

开发者 https://www.devze.com 2023-03-08 10:06 出处:网络
I\'m converting a Guid to a BigInteger so I can base62 encode it.开发者_如何学PythonThis works well, however, I can get negative numbers in BigInterger.How do I shift the BigInteger so the number is p

I'm converting a Guid to a BigInteger so I can base62 encode it.开发者_如何学Python This works well, however, I can get negative numbers in BigInterger. How do I shift the BigInteger so the number is positive. I'll also need to be able to shift it back so I can convert back to a Guid.

// GUID is a 128-bit signed integer 
Guid original = new Guid("{35db5c21-2d98-4456-88a0-af263ed87bc2}");
BigInteger b = new BigInteger(original.ToByteArray());

// shift so its a postive number?


Note: For url-safe version of Base64 consider using modifyed set of characters for Base64 ( http://en.wikipedia.org/wiki/Base64#URL_applications) instead of custom Base62.

I believe you can append 0 to the array first (will make higest byte always not to contain 1 in the highest bit) and then convert to BigInteger if you really need positive BigInteger.


do you mean base64 encode?

Convert.ToBase64String(Guid.NewGuid().ToByteArray());


If you sometimes get negative numbers, it means that your GUID value is large enough to fill all 128 bits of the BigInteger or else the BigInteger byte[] ctor is interpreting the data as such. To make sure your bytes are actually positive, check that you are getting <= 16 bytes (128 bits) and that the most-significant bit of the last byte (because it's little endian) is zero. If you have <16 bytes, you can simply append a zero byte to your array (again, append because it is little endian) to make sure the BigInteger ctor treats it as a positive number.


This article I think it can give you the solution: In summary it is to add one more byte, to 0, if the most significant bit of the last byte is a 1

Guid original = Guid.NewGuid();
byte[] bytes = original.ToByteArray();
if ((bytes[bytes.Length - 1] & 0x80) > 0) 
{
   byte[] temp = new byte[bytes.Length];
   Array.Copy(bytes, temp, bytes.Length);
   bytes = new byte[temp.Length + 1];
   Array.Copy(temp, bytes, temp.Length);
}

BigInteger guidPositive = new BigInteger(bytes);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号