Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to Format a Number to a Hexicadecimal with a Prefix '0x'

Tags:

c#

format

hex

How to Format a Number to a Hexicadecimal with a Prefix '0x'?

Such as:

int space = 32;
MessageBox.Show(space.ToString("'0x'X4")); // Output 0xX4 instead of 0x0020

I followed this link: Custom Numeric Format Strings http://msdn.microsoft.com/en-us/library/0c899ak8.aspx Literal string delimiter: Indicates that the enclosed characters should be copied to the result string unchanged. But it does not work for 'X4' (it does work for '#'), kind of weird.

I'm using it in a DataGridView.DefaultCellStyle.Format, so I cannot use:

"0x{0:X4}", space

Thanks. Peter

like image 226
Peter Lee Avatar asked Oct 25 '10 06:10

Peter Lee


2 Answers

int space = 32;
MessageBox.Show("0x"+space.ToString("X"));

If you want to output 0x0020:

MessageBox.Show("0x"+space.ToString("X4"));
like image 172
Andrew Rokicki Avatar answered Nov 17 '22 06:11

Andrew Rokicki


string.Format("0x{0:x8}", ii);
like image 24
Romerik Rousseau Avatar answered Nov 17 '22 05:11

Romerik Rousseau