开发者

c#: Convert hex to GUID

开发者 https://www.devze.com 2023-02-18 02:02 出处:网络
Is there any way in C# to convert HEX to GUID? Example: I want to create a GUID with value equal to 0xa145ce546fe5bbcf1745491b50a4233d19b8223c0a743cad6847142df8b63821开发者_如何学Go640beeabe82824b7d

Is there any way in C# to convert HEX to GUID?

Example:

I want to create a GUID with value equal to 0xa145ce546fe5bbcf1745491b50a4233d19b8223c0a743cad6847142df8b63821开发者_如何学Go640beeabe82824b7d2bf507cb487


If you know it's a valid GUID in one of these formats:

dddddddddddddddddddddddddddddddd 
dddddddd-dddd-dddd-dddd-dddddddddddd 
{dddddddd-dddd-dddd-dddd-dddddddddddd} 
(dddddddd-dddd-dddd-dddd-dddddddddddd) 
{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} 

Then new Guid(hexstring).

If you don't know for sure then with .NET4.0 you can use:

Guid g = default(Guid);
bool success = Guid.TryParse(hexstring, out g);

Otherwise you'll have to wrap the first in a try block, or check the format yourself first (e.g. with a Regex).

Edit:

Your edited question can't be done, you can't fit a quart into a pint-glass. There's enough bits of information in that for nearly 3 Guids.


The Guid(string) constructor can parse string with GUIDs in several formats, e.g.:

string hex = Guid.NewGuid().ToString("N");

// hex == "ca761232ed4211cebacd00aa0057b223"

Guid guid = new Guid(hex);

See also: Parse, ParseExact, TryParse, TryParseExact


There are several constructors for Guid that you could use as well as Parse and ParseExact if you have a hex string.

EDIT: Given your edit, you could use a BigInteger but without knowing why you want a Guid, it's hard to give a better answer.

//untested
var bytes = new byte[] {Oxa,1,4,5,Oxc,Oxe,5,4,6,Oxf,Oxe,5,Oxb,Oxb,Oxc,Oxf,1,7,4,5,4,9,1,Oxb,5,0,Oxa,4,2,3,3,Oxd,1,9,Oxb,8,2,2,3,Oxc,0,Oxa,7,4,3,Oxc,Oxa,Oxd,6,8,4,7,14,2,Oxd,Oxf,8,Oxb,6,3,8,2,1,6,4,0,Oxb,Oxe,Oxe,Oxa,Oxb,Oxe,8,2,8,2,4,Oxb,7,Oxd,2,Oxb,Oxf,5,0,7,Oxc,Oxb,4,8,7};
var bigInteger = new BigInteger(bytes);


I suspect the following should do the trick:

Guid g = new Guid(str); // Where str is the hex string

Of course you will need a try catch block around it in case str isn't well formed.

0

精彩评论

暂无评论...
验证码 换一张
取 消