MSDN将字节数组转换为十六进制值字符串时 Byte 的用法

示例

[Visual Basic, C#] 下面的示例说明将字节数组转换为十六进制值字符串时 Byte 的用法。

[Visual Basic] 
Class HexTest

   Private Shared hexDigits As Char() =  {"0"c, "1"c, "2"c, "3"c, "4"c, "5"c, "6"c, "7"c, "8"c, "9"c, "A"c, "B"c, "C"c, "D"c, "E"c, "F"c}
   
   Public Shared Function ToHexString(bytes() As Byte) As String

      Dim hexStr As String = ""
      Dim i As Integer
      For i = 0 To bytes.Length - 1
     hexStr = hexStr + Hex(bytes(i))
      Next i
      Return hexStr 

   End Function 'ToHexString

  
   Shared Sub Main()
      
      Dim b As Byte() =  {&H0, &H12, &H34, &H56, &HAA, &H55, &HFF}
      Console.WriteLine(ToHexString(b))

   End Sub 'Main

End Class 'HexTest

 

[C#] 
class HexTest
{
    static char[] hexDigits = {
        '0', '1', '2', '3', '4', '5', '6', '7',
        '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
 
    public static string ToHexString(byte[] bytes) {
        char[] chars = new char[bytes.Length * 2];
        for (int i = 0; i < bytes.Length; i++) {
            int b = bytes[i];
            chars[i * 2] = hexDigits[b >> 4];
            chars[i * 2 + 1] = hexDigits[b & 0xF];
        }
        return new string(chars);
    }
 
    static void Main() {

        byte[] b = {0x00, 0x12, 0x34, 0x56, 0xAA, 0x55, 0xFF};
        Console.WriteLine(ToHexString(b));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值