In c# I have Error codes defined as
public const uint SOME_ERROR= 0x80000009;
I want to write the 0x80000009 to a text file, right now I am trying
private static uint ErrorCode;
ErrorCode = SomeMethod();
string message = "Error: {0}.";
message = string.Format(message, ErrorCode);
But that writes it out as a int such as "2147483656" how can I get it to write out as the hex to a text file?
You need to use X
format specifier to output uint
as hexadecimal.
So in your case:
String.Format(message, ErrorCode.ToString("X"));
Or
string message = "Error: {0:X}."; // format supports format specifier after colon
String.Format(message, ErrorCode);
In C# 6 and newer, you can also use string interpolation:
string message = $"Error: {ErrorCode:X}";
You might also want to use X8
with 8 specifying the required number of characters so that all error codes are aligned. uint
is 4 bytes large, each byte can be represented with 2 hex chars, therefore 8 hex chars for uint
in total.
string message = $"Error: {ErrorCode:X8}";
See Custom numeric format specifiers at Microsoft Docs for further details.
You dont have to cast it. Simply do
message = string.Format(message, ErrorCode);
and if your method SomeMethod()
is returning an int
then you can convert your int to Hex like this:
message = string.Format(message, ErrorCode.ToString("X"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With