I am trying to convert a Decimal to Hex as a string. I've looked all over for a solution to this, but all I can find is Int or long to Hex. When using the code below I receive a "Format specifier was invalid" error.
Decimal decValue = 18446744073709551615
string hexValue = decValue.ToString("X");
I've also looked into converting the decimal to a byte array and then converting to Hex, but I'm coming up short on that also.
Since you're using .NET 3.5, how about IntX which will work for .NET 2.0+?
var intx = new Oyster.Math.IntX(decValue.ToString());
intx.ToString(16);
For .NET 4.0+ use System.Numerics
(remember to include System.Numerics.dll
)
Decimal decValue = 18446744073709551615;
var bigValue = new BigInteger(decValue);
bigValue.ToString("X");
Of course this ignores any portion that is non-integer.
Since you're using .NET 3.5, you'll have to do it by hand. You can wrap it up nice and neat in an extension method:
public static class DecimalHelper {
public static string ToHexString( this Decimal dec ) {
var sb = new StringBuilder();
while( dec > 1 ) {
var r = dec % 16;
dec /= 16;
sb.Insert( 0, ((int)r).ToString( "X" ) );
}
return sb.ToString();
}
}
Then just call it like this:
Decimal dec = 18446744073709551615;
var hex = dec.ToHexString();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.