-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathHexConverter.cs
More file actions
73 lines (65 loc) · 2.66 KB
/
HexConverter.cs
File metadata and controls
73 lines (65 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Copyright (c) BootstrapBlazor & Argo Zhang (argo@live.ca). All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Website: https://www.blazor.zone or https://argozhang.github.io/
namespace BootstrapBlazor.Socket.DataConverters;
/// <summary>
/// 十六进制 与 Byte 数组转换方法
/// </summary>
public static class HexConverter
{
/// <summary>
/// 将 byte[] 转为 16 进制字符串
/// <para>Converts a byte array to its hexadecimal string representation.</para>
/// </summary>
/// <param name="bytes">The byte array to convert.</param>
/// <param name="separator"></param>
/// <param name="upper"></param>
/// <returns>A string containing the hexadecimal representation of the byte array.</returns>
public static string ToString(byte[]? bytes, string? separator = "-", bool upper = true)
{
if (bytes == null || bytes.Length == 0)
{
return string.Empty;
}
if (separator == "-")
{
return BitConverter.ToString(bytes);
}
return string.Join(separator, bytes.Select(i => upper ? i.ToString("X2") : i.ToString("x2")));
}
/// <summary>
/// 将 byte[] 转为 16 进制字符串
/// <para>Converts a byte array to its hexadecimal string representation.</para>
/// </summary>
/// <param name="span"></param>
/// <param name="separator"></param>
/// <param name="upper"></param>
/// <returns></returns>
public static string ToString(ReadOnlySpan<byte> span, string? separator = "-", bool upper = true) => ToString(span.ToArray(), separator, upper);
/// <summary>
/// 将字符串转换为字节数组
/// </summary>
/// <param name="str"></param>
/// <param name="separator"></param>
/// <param name="options"></param>
/// <returns></returns>
public static byte[] ToBytes(string str, string? separator = null, StringSplitOptions options = StringSplitOptions.None)
{
// 把 str 内的 delimiter 符号替换掉
if (!string.IsNullOrEmpty(separator))
{
str = string.Join("", str.Split(separator, options));
}
// 把 Hex 形式的 str 转化为 byte[]
if (str.Length % 2 != 0)
{
throw new ArgumentException("The raw string cannot have an odd number of digits. 参数 str 位数不正确无法转化为 16 进制字节数组", nameof(str));
}
var bytes = new byte[str.Length / 2];
for (var i = 0; i < bytes.Length; i++)
{
bytes[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
}
return bytes;
}
}