c# - 128位整数的指南

标签 c# python-2.7

我需要将一个 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/

相关文章:

c# - 我可以以编程方式启动 "services.msc"并将用户集中在确切的服务上吗?

python : How to remove widget in kivy

python - 使用 UnicodeWriter 时可怕的 "ordinal not in range"——否则文件会干净地写入/读取

c# - WPF DataGrid 和多线程

c# - 如何使用POST从客户端向服务器发送数据?

c# - .NET Compact Framework 3.5 是否有 BackgroundWorker 替代品?

python - Pandas:欧式date_range

python - 使用 Python "imgdiff"库查找两个图像之间的差异百分比

python-2.7 - 权限被拒绝错误 13 - Hadoop 上的 Python

c# - Entity Framework VS 纯 Ado.Net