gpt4 book ai didi

C# 将 Active Directory 十六进制转换为 GUID

转载 作者:太空宇宙 更新时间:2023-11-03 12:02:07 25 4
gpt4 key购买 nike

我们正在将 AD 对象推送到第 3 方供应商,其中 objectGUID 属性以十六进制形式输出,如“属性编辑器”窗口中所示。我们需要能够将十六进制转换回 GUID 格式,以便我们可以对数据库执行查找。

是否可以将十六进制转换回 GUID 格式?很有可能,十六进制将以字符串格式返回。

例子:

Hexadecimal: EC 14 70 17 FD FF 0D 40 BC 03 71 A8 C5 D9 E3 02
or
Hexadecimal (string): ec147017fdff0d40bc0371a8c5d9e302

GUID: 177014EC-FFFD-400D-BC03-71A8C5D9E302

更新

接受答案后,我可以使用 Microsoft 的一些代码对其进行验证 See here: Guid.ToByteArray Method

using System;

namespace ConsoleApp3
{
class Program
{
static void Main()
{
// https://stackoverflow.com/questions/56638890/c-sharp-convert-active-directory-hexadecimal-to-guid
byte[] bytearray = StringToByteArray("ec147017fdff0d40bc0371a8c5d9e302");

// https://learn.microsoft.com/en-us/dotnet/api/system.guid.tobytearray?view=netframework-4.8
Guid guid = new Guid(bytearray);
Console.WriteLine("Guid: {0}", guid);
Byte[] bytes = guid.ToByteArray();
foreach (var byt in bytes)
Console.Write("{0:X2} ", byt);

Console.WriteLine();
Guid guid2 = new Guid(bytes);
Console.WriteLine("Guid: {0} (Same as First Guid: {1})", guid2, guid2.Equals(guid));
Console.ReadLine();

}

public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
}
}

最佳答案

Guid has a constructor which takes a byte array

您可以将十六进制的 string 转换为字节数组,并使用它来构造一个新的 Guid

如果您需要了解如何将十六进制字符串转换为字节数组,Stack Overflow already has a few answers to that question .

来自该问题的公认答案:

public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}

关于C# 将 Active Directory 十六进制转换为 GUID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56638890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com