开发者

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

开发者 https://www.devze.com 2023-02-19 09:11 出处:网络
I can turn a byte开发者_Python百科 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 for

I can turn a byte开发者_Python百科 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?


myByte.ToString("X2") I believe.


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]);
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消