C#教程
主页 > 软件编程 > C#教程 >

C#操作Byte数组和十六进制进行互转

2022-05-03 | 秩名 | 点击:

一、Byte 数组转十六进制字符串

1

2

3

4

5

6

7

8

9

10

11

12

13

14

/// <summary>

/// Byte 数组转十六进制字符串

/// </summary>

/// <param name="Bytes"></param>

/// <returns></returns>

public static string ByteToHex(byte[] Bytes)

{

    string str = string.Empty;

    foreach (byte Byte in Bytes)

    {

        str += String.Format("{0:X2}", Byte) + " ";

    }

    return str.Trim();

}

二、字符串转十六进制Byte数组

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

/// <summary>

/// 字符串转十六进制Byte数组

/// </summary>

/// <param name="hexString"></param>

/// <returns></returns>

public static byte[] strToToHexByte(string hexString)

{

    try

    {

        hexString = hexString.Replace(" ", "");

        if ((hexString.Length % 2) != 0)

            hexString += " ";

        byte[] returnBytes = new byte[hexString.Length / 2];

        for (int i = 0; i < returnBytes.Length; i++)

            returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);

        return returnBytes;

    }

    catch

    {

        return null;

    }

 

}

原文链接:https://www.cnblogs.com/wml-it/p/15976903.html
相关文章
最新更新