Turn byte into two-digit hexadecimal number just using ToString?

C#.NetString Formatting

C# Problem Overview


I can turn a byte into a hexadecimal number like this:

myByte.ToString("X")

but it will have only one digit if it is less than 0x10. I need it with a leading zero. Is there a format string that makes it possible to do this in a single call to ToString?

C# Solutions


Solution 1 - C#

myByte.ToString("X2") I believe.

Solution 2 - C#

Maybe you like to do it as below:

private static void byte2hex(byte b, StringBuilder buf)
    {
        char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                            'A', 'B', 'C', 'D', 'E', 'F' };
        int high = ((b & 0xf0) >> 4);
        int low = (b & 0x0f);
        buf.Append(hexChars[high]);
        buf.Append(hexChars[low]);
    }

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
QuestionTimwiView Question on Stackoverflow
Solution 1 - C#Roman StarkovView Answer on Stackoverflow
Solution 2 - C#Ali TofighView Answer on Stackoverflow