8

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?

Lawtonj94
  • 309
  • 1
  • 5
  • 16

2 Answers2

9

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.

Zdeněk Jelínek
  • 2,611
  • 1
  • 17
  • 23
3

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"));
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331