Convert int to hex with leading zeros

C#HexString Formatting

C# Problem Overview


How to convert int (4 bytes) to hex ("XX XX XX XX") without cycles?

for example:

i=13 hex="00 00 00 0D"

i.ToString("X") returns "D", but I need a 4-bytes hex value.

C# Solutions


Solution 1 - C#

You can specify the minimum number of digits by appending the number of hex digits you want to the X format string. Since two hex digits correspond to one byte, your example with 4 bytes needs 8 hex digits. i.e. use i.ToString("X8").

If you want lower case letters, use x instead of X. For example 13.ToString("x8") maps to 0000000d.

Solution 2 - C#

try this:

int innum = 123;
string Hex = innum .ToString("X");  // gives you hex "7B"
string Hex = innum .ToString("X8");  // gives you hex 8 digit "0000007B"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2264990View Question on Stackoverflow
Solution 1 - C#CodesInChaosView Answer on Stackoverflow
Solution 2 - C#KF2View Answer on Stackoverflow