将 128 位有符号 BigInteger 转换为始终为正数
我正在将 Guid 转换为 BigInteger,以便可以对其进行 base62 编码。这很有效,但是,我可以在 BigInterger 中得到负数。如何移动 BigInteger 以使数字为正数。我还需要能够将其移回来,以便我可以转换回 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?
I'm converting a Guid to a BigInteger so I can base62 encode it. 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
注意:对于 Base64 的 URL 安全版本,请考虑使用经过修改的 Base64 字符集 ( http://en .wikipedia.org/wiki/Base64#URL_applications)而不是自定义 Base62。
我相信你可以先将 0 附加到数组中(将使最高字节始终不包含最高位中的 1),然后如果你确实需要正 BigInteger,则转换为 BigInteger。
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.
你的意思是base64编码吗?
do you mean base64 encode?
如果有时得到负数,则意味着您的 GUID 值足够大,可以填充 BigInteger 的所有 128 位,否则 BigInteger byte[] 构造函数将按此方式解释数据。为了确保您的字节实际上是正数,请检查您是否获得 <= 16 字节(128 位),并且最后一个字节的最高有效位(因为它是小端字节序)是否为零。如果您有 <16 个字节,则只需向数组附加一个零字节 (再次追加,因为它是小端)以确保 BigInteger ctor 将其视为正数。
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.
这篇文章 我认为它可以给你解决方案:
总而言之,如果最后一个字节的最高有效位是 1,则再添加一个字节为 0
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