tags:

views:

414

answers:

2

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;
}
+13  A: 

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.

cyberzed
Beat me to it :o) Also, found this. Similar question:http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/d14da7dc-6258-42a1-b660-d18bdf9635b8
Ardman
Haha, awesome. return "0x" + ouid.ToString("x").ToUpper(); <3
Langdon
I'll actually be helpfull...so you can skip all the BitConverter, etc.return string.Format("0x{0:x}", temp);If you even wanna write an extension for that purpose (which i wouldn't) :D
cyberzed
No need for the ToUpper()...just us X instead of x matey :)
cyberzed
@Ardman, it's funny... in all my google searching I never actually searched for "ulong to hex", I kept typing UInt64 in all my searches. Google needs synonym searches.
Langdon
May I suggest having a look at NumberFormatInfo just like CultureInfo, those two classes are often overlooked by people cause they tend to think there is no help for that kindda stuff :)
cyberzed
@Langdon - google HAS synonym searches http://www.googleguide.com/synonym_operator.html
dss539
+3  A: 

you can use string.format....

string.Format("0x{0:X4}",200);

check here for a more comprehensive "how-to" on formatting output

Muad'Dib