【问题标题】:Shift a 128-bit signed BigInteger to always be positive将 128 位有符号 BigInteger 转换为始终为正数
【发布时间】:2011-05-26 16:17:18
【问题描述】:

我正在将 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?

【问题讨论】:

  • 只是好奇:使用 GUID 字符串本身有什么问题?

标签: c# biginteger


【解决方案1】:

注意:对于 Base64 的 url 安全版本,请考虑使用修改后的 Base64 字符集 (http://en.wikipedia.org/wiki/Base64#URL_applications) 而不是自定义 Base62。

我相信您可以先将 0 附加到数组(将使最高字节始终不包含最高位中的 1),然后如果您确实需要正 BigInteger,则将其转换为 BigInteger。

【讨论】:

    【解决方案2】:

    你的意思是base64编码吗?

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

    【讨论】:

    • 不,我有一个自定义的 base62 编码。只需要一种方法来可靠地让 BigInteger 始终为正数。
    【解决方案3】:

    如果您有时会得到负数,则意味着您的 GUID 值足够大,可以填充 BigInteger 的所有 128 位,否则 BigInteger byte[] ctor 正在解释数据。为确保您的字节实际上是正数,请检查您是否得到 append a zero byte to your array(再次附加,因为它是小端序)以确保 BigInteger ctor 将其视为正数。

    【讨论】:

      【解决方案4】:

      这个article我觉得可以给你解决方案: 总而言之,如果最后一个字节的最高有效位是 1,则在 0 上再加一个字节

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

      【讨论】:

        猜你喜欢
        • 2012-12-20
        • 1970-01-01
        • 2017-09-04
        • 1970-01-01
        • 2021-10-06
        • 1970-01-01
        • 1970-01-01
        • 2022-01-13
        • 1970-01-01
        相关资源
        最近更新 更多