Writing uint out as Hex not Int

5

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?

c#
hex
asked on Stack Overflow Nov 2, 2015 by Lawtonj94 • edited Nov 2, 2015 by Lawtonj94

2 Answers

5

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.

answered on Stack Overflow Nov 2, 2015 by Zdeněk Jelínek • edited Nov 5, 2020 by Zdeněk Jelínek
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"));
answered on Stack Overflow Nov 2, 2015 by Rahul Tripathi • edited Nov 2, 2015 by Rahul Tripathi

User contributions licensed under CC BY-SA 3.0