c#: Convert hex to GUID - c#

Is there any way in C# to convert HEX to GUID?
Example:
I want to create a GUID with value equal to
0xa145ce546fe5bbcf1745491b50a4233d19b8223c0a743cad6847142df8b63821640beeabe82824b7d2bf507cb487

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.

Related

Format a string like you would a numeric value

I have a string that I would like to format the same way I would a numeric value.
Ex:
int num = 2;
string option = num.ToString("000");
Console.WriteLine(option);
//output
//002
But the only way I can think to format it is to parse it as an int, then apply the ToString("000") method to it.
string option = "2";
option = int.Parse(option).ToString("000");
Is there a better, more direct way to do this?
No, there is no built-in mechanism to "format" a string as if it were a number. Some options:
Use string functions (Pad, Length, Substring) to determine what characters should be added
Parse to a numeric type and use ToString with numeric formatting strings
Use a reqular expression to extract the digits and generate a new string
There's not one "right" answer. Each has risks and benefits in terms of safety (what if the string does not represent a valid integer?), readability, performance, etc.
Would this suit your requirement?
string x = "2";
string formattedX = x.PadLeft(3, '0');
Console.WriteLine(formattedX); //prints 002

Input string was not in a correct format. When i try to convert char->string->int

I have the following code inside my asp.net vmc web application :-
var getNumbers = (from t in ut.newTag
where char.IsDigit(t)
select t).ToString();
tech.PartialTag = Convert.ToInt32(getNumbers);
but i am getting the following exception :-
Input string was not in a correct format.
so can anyone advice how i can solve this issue??
getNumbers is a string, containing type name of string enumerator It will look like
"System.Linq.Enumerable+WhereSelectArrayIterator`1[System.String,System.String]"
You obviously can't convert that type name to integer. If you want to try parse newTag and assign it to PartialTag if there is an integer:
int value;
if (Int32.TryParse(ut.newTag, out value))
tech.PartialTag = value;
There's a ctor of String taking a char[] as parameter, so
var getNumbers = new String((from t in ut.newTag
where char.IsDigit(t)
select t).ToArray());
tech.PartialTag = Convert.ToInt32(getNumbers);
Difference with Sergey's answer :
if your input is 1A2 for example, Sergey's solution won't accept the input.
But my solution (based on yours) will take 12.
So, it depends on what you need (I think Sergey's one is clearer, it just rejects non integers inputs).

String to number generator

I m looking for a way to convert a string to a unique Id.
Ideas invited for an algorithm that comes up with a unique number for each string sent to it.
I tried to use hash code but then realized that two strings could have the same hash code.
How do I generate a unique code for each string as input and two same strings should generate me the same id at all times.
Can you have characters in your "unique ID"? If so, this should work ;-)
public string MakeUnique(string s)
{
return s;
}
All ID's will be unique to the value provided. The same string, will produce the exact same ID. That's what you wanted right?
If it's an integer result you want, how about converting each character to an int...
public int MakeUnique(string s)
{
string result = "";
foreach(var c in s)
{
result += ((int)c).ToString();
}
return Int.Parse(result);
}
WARNING: This will break if the string is too big
Simply append or prepend a guid:
string foo = "MyString";
//Simply throw it on the end
string uniqueString = foo + Guid.NewGuid();
//Prepend with underscore
string uniqueString = String.Format("{0}_{1}", foo, Guid.NewGuid());
//Append with underscore
string uniqueString = String.Format("{0}_{1}", Guid.NewGuid(), foo);
Edit (new requirement)
You have not provided enough information for me to post a great answer to this question. For example, environment (web, winforms, etc.) would be beneficial.
To point you in the right direction...
If the unique string that is returned needs to be the same when you pass in a string a second time, you could maintain a history of generated strings and check it each time generation is requested.
Truthfully, there are lots of ways to skin this cat...
If the original string is sensitive, similar to Gravatar, you could encrypt the string with MD5 encryption
As you have stated, and #Austin Salonen commented, they're not 100% unique, but the risk is low:
How are hash functions like MD5 unique?
A string can be fairly long and consists of charactes, which are 16-bit values. The number of possible strings is huge (much more than the range of integer or Guid). So you can't have a function that "just" translates a string into some guaranteed unique code, without some help.
You could use a database table: lookup your string in the table. If it's not there, insert it, generating a new (sequential) unique id. If it's there, use that id. The number of possible strings is huge, the number of strings you encounter, probably not.

Convert alphabetic string into Integer in C#

Is it possible to convert alphabetical string into int in C#? For example
string str = "xyz";
int i = Convert.ToInt32(str);
I know it throws an error on the second line, but this is what I want to do.
So how can I convert an alphabetical string to integer?
Thanks in advance
System.Text.Encoding ascii = System.Text.Encoding.ASCII;
string str = "xyz";
Byte[] encodedBytes = ascii.GetBytes(str);
foreach (Byte b in encodedBytes)
{
return b;
}
this will return each characters ascii value... its up to you what you want to do with them
To answer the literal questions that you have asked
Is it possible to convert alphabetical string into int in C#?
Simply put... no
So how can I convert an alphabetical string to integer?
You cannot. You can simply TryParse to see if it will parse, but unless you calculate as ASCII value from the characters, there is no built in method in c# (or .NET for that matter) that will do this.
You can check whether a string contains a valid number using Int32.TryParse (if your questions is about avoiding an exception to be thrown):
int parsed;
if (!Int32.TryParse(str, out parsed))
//Do Something

Code Golf: C#: Convert ulong to Hex String

I tried writing an extension method to take in a ulong and return a string that represents the provided value in hexadecimal format with no leading zeros. I wasn't really happy with what I came up with... is there not a better way to do this using standard .NET libraries?
public static string ToHexString(this ulong ouid)
{
string temp = BitConverter.ToString(BitConverter.GetBytes(ouid).Reverse().ToArray()).Replace("-", "");
while (temp.Substring(0, 1) == "0")
{
temp = temp.Substring(1);
}
return "0x" + temp;
}
The solution is actually really simple, instead of using all kinds of quirks to format a number into hex you can dig down into the NumberFormatInfo class.
The solution to your problem is as follows...
return string.Format("0x{0:X}", temp);
Though I wouldn't make an extension method for this use.
You can use string.format:
string.Format("0x{0:X4}",200);
Check String Formatting in C# for a more comprehensive "how-to" on formatting output.
In C# 6 you can use string interpolation:
$"0x{variable:X}"
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

Categories

Resources