Code Golf: C#: Convert ulong to Hex String - c#

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

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

c#: Convert hex to GUID

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.

Base64 in C# and PL/SQL?

In PL/SQL how can I convert a string (long HTML string with new line and tags, etc) to Base64 that is easy to decrypt in C#?
In C# there are:
Convert.ToBase64String()
Convert.ToBase64CharArray()
BitConverter.ToString()
which one is compatible with PL/SQL
utl_encode.base64_encode();
?
I welcome any other suggestions :-)
You'll probably want to use this method:
Convert.ToBase64String()
It returns a Base64 encoded String based off an array of unsigned 8-bit integers (bytes).
As an alternate, you can use Convert.ToBase64CharArray(), but the output is a character array, which is a bit odd but may be useful in certain circumstances.
The method BitConverter.ToString() returns a String, but the bytes are represented in Hexadecimal, not Base64 encoded.
I done it :-)
PL/SQL
s1 varchar2(32767);
s2 varchar2(32767);
s2:= utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw(s1)));
s2:= utl_raw.cast_to_varchar2(utl_encode.base64_decode(utl_raw.cast_to_raw(s1)));
are compatible with C#
public static string ToBase64(string str)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(str));
}
//++++++++++++++++++++++++++++++++++++++++++++++
public static string FromBase64(string str)
{
return Encoding.UTF8.GetString(Convert.FromBase64String(str));
}
hope you find it useful :-)

string.Format() Blank Zero

In my application, there are possibilities to format a string using the string.Format() function. I want to add the possibility to return blank when the result is zero.
As far as I can see, it is possible to do this using the code: 0.toString("0;; ");, but as i already mentioned, I need to use the string.Format() function (since it must be able to use for example the {0:P} format for percentage.
Does anyone knows how to blank a zero value using the string.Format() function?
String.Format() supports the ; section separator.
Try e.g. String.Format("{0:#%;;' '}", 0);.
My answer is a bit late, but you may want to try the following:
{0:#.##%;-#.##%;''}
why don't you do it with if else statement?
string result = String.Format(the value);
if(result=="0")
{
result=" ";
}
Or, perhaps more elegantly as an extension method on int:
public static class StringFormatters
{
public static string ToNonZeroString(this int i) => i == 0 ? "" : i.ToString();
}
and then
(1+1-2).ToNonZeroString()

Best way to decode hex sequence of unicode characters to string

I'm working with C# .Net
I would like to know how to convert a Unicode form string like "\u1D0EC"
(note that it's above "\uFFFF") to it's symbol... "𝃬"
Thanks For Advance!!!
That Unicode codepoint is encoded in UTF32. .NET and Windows encode Unicode in UTF16, you'll have to translate. UTF16 uses "surrogate pairs" to handle codepoints above 0xffff, a similar kind of approach as UTF8. The first code of the pair is 0xd800..dbff, the second code is 0xdc00..dfff. Try this sample code to see that at work:
using System;
using System.Text;
class Program {
static void Main(string[] args) {
uint utf32 = uint.Parse("1D0EC", System.Globalization.NumberStyles.HexNumber);
string s = Encoding.UTF32.GetString(BitConverter.GetBytes(utf32));
foreach (char c in s.ToCharArray()) {
Console.WriteLine("{0:X}", (uint)c);
}
Console.ReadLine();
}
}
Convert each sequence with int.Parse(String, NumberStyles) and char.ConvertFromUtf32:
string s = #"\U1D0EC";
string converted = char.ConvertFromUtf32(int.Parse(s.Substring(2), NumberStyles.HexNumber));
I have recently push my FOSS Uncode Converter at Codeplex (http://unicode.codeplex.com)
you can convert whatever you want to Hex code and from Hex code to get the right character, also there is a full information character database.
I use this code
public static char ConvertHexToUnicode(string hexCode)
{
if (hexCode != string.Empty)
return ((char)int.Parse(hexCode, NumberStyles.AllowHexSpecifier));
char empty = new char();
return empty;
}//end
you can see entire code on the http://unicode.codeplex.com/
It appears you just want this in your code... you can type it as a string literal using the escape code \Uxxxxxxxx (note that this is a capital U, and there must be 8 digits). For this example, it would be: "\U0001D0EC".

Categories

Resources