Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing uint out as Hex not Int [duplicate]

Tags:

c#

hex

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?

like image 550
Lawtonj94 Avatar asked Nov 02 '15 10:11

Lawtonj94


2 Answers

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.

like image 136
Zdeněk Jelínek Avatar answered Oct 03 '22 00:10

Zdeněk Jelínek


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"));
like image 37
Rahul Tripathi Avatar answered Oct 02 '22 22:10

Rahul Tripathi