我需要将一个 guid 转换为一个大整数..这很好,但是在测试过程中我已经突出显示了一些我需要向我解释的东西 ;)
如果我执行以下操作:
var g = Guid.NewGuid(); // 86736036-6034-43c5-9b85-1c833837dbea
var p = g.ToByteArray();
var x = new BigInteger(p); // -28104782885366703164142972435490971594
但是如果我在 python 中这样做......我会得到不同的结果:
import uuid
x = uuid.UUID('86736036-6034-43c5-9b85-1c833837dbea')
print x
print x.int # 178715616993326703606264498842288774122
对 python 和 .net 有更好了解的人可以帮忙解释一下吗?
最佳答案
将 GUID 编码为其组成字节是一种非标准化操作,即 dealt with differently on Windows/Microsoft platforms (IMO 以一种最令人困惑的方式)。
var g = Guid.Parse("86736036-6034-43c5-9b85-1c833837dbea");
var guidBytes = $"0{g:N}"; //no dashes, leading 0
var pythonicUuidIntValue = BigInteger.Parse(guidBytes, NumberStyles.HexNumber);
将为您提供来自 C# 的 pythonic 值
.ToByteArray
失败的原因隐含在 the instructions 中:
The order of the beginning four-byte group and the next two two-byte groups is reversed, whereas the order of the last two-byte group and the closing six-byte group is the same.
知道了这一点,就有可能编写一个不涉及遍历字符串的方法。读者练习。
关于c# - 128位整数的指南,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50679214/