Skip to content

Commit f4bd614

Browse files
committed
feat: 增加 HexConverter 类
1 parent e4236c0 commit f4bd614

1 file changed

Lines changed: 70 additions & 0 deletions

File tree

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// Copyright (c) BootstrapBlazor & Argo Zhang (argo@live.ca). All rights reserved.
2+
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3+
// Website: https://www.blazor.zone or https://argozhang.github.io/
4+
5+
using System.Text;
6+
7+
namespace BootstrapBlazor.Components.DataConverter;
8+
9+
/// <summary>
10+
/// Byte 数组扩展方法
11+
/// </summary>
12+
public static class HexConverter
13+
{
14+
/// <summary>
15+
/// 将 byte[] 转为 16 进制字符串
16+
/// <para>Converts a byte array to its hexadecimal string representation.</para>
17+
/// </summary>
18+
/// <param name="bytes">The byte array to convert.</param>
19+
/// <param name="separator"></param>
20+
/// <returns>A string containing the hexadecimal representation of the byte array.</returns>
21+
public static string ToString(byte[]? bytes, string? separator = "-")
22+
{
23+
if (bytes == null || bytes.Length == 0)
24+
{
25+
return string.Empty;
26+
}
27+
28+
if (separator == "-")
29+
{
30+
return BitConverter.ToString(bytes);
31+
}
32+
33+
var sb = new StringBuilder(bytes.Length * 3);
34+
foreach (var b in bytes)
35+
{
36+
sb.Append(b.ToString("X2"));
37+
sb.Append(separator);
38+
}
39+
return sb.ToString(0, sb.Length - 1);
40+
}
41+
42+
/// <summary>
43+
/// 将字符串转换为字节数组
44+
/// </summary>
45+
/// <param name="str"></param>
46+
/// <param name="separator"></param>
47+
/// <param name="options"></param>
48+
/// <returns></returns>
49+
public static byte[] ToByte(string str, string? separator = null, StringSplitOptions options = StringSplitOptions.None)
50+
{
51+
// 把 str 内的 delimiter 符号替换掉
52+
if (!string.IsNullOrEmpty(separator))
53+
{
54+
str = string.Join("", str.Split(separator, options));
55+
}
56+
57+
// 把 Hex 形式的 str 转化为 byte[]
58+
if (str.Length % 2 != 0)
59+
{
60+
throw new ArgumentException("The raw string cannot have an odd number of digits. 参数 str 位数不正确无法转化为 16 进制字节数组", nameof(str));
61+
}
62+
63+
var bytes = new byte[str.Length / 2];
64+
for (var i = 0; i < bytes.Length; i++)
65+
{
66+
bytes[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
67+
}
68+
return bytes;
69+
}
70+
}

0 commit comments

Comments
 (0)