Skip to content

Commit 03a2f9e

Browse files
committed
💾 Feat(Ext): For byte[], you can easily convert to string now.
1 parent dab916e commit 03a2f9e

1 file changed

Lines changed: 82 additions & 0 deletions

File tree

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
using System.Text;
2+
3+
namespace Common.BasicHelper.Utils.Extensions;
4+
5+
public static class BinaryHelper
6+
{
7+
/// <summary>
8+
/// 二进制内容转 UTF8 字符串
9+
/// </summary>
10+
/// <param name="content">字节数组</param>
11+
/// <param name="index">内容起始下标</param>
12+
/// <param name="count">内容长度</param>
13+
/// <returns>UTF8 字符串</returns>
14+
public static string ToUTF8(this byte[] content, int? index = null, int? count = null)
15+
{
16+
if (index is null || count is null)
17+
return Encoding.UTF8.GetString(content);
18+
else
19+
return Encoding.UTF8.GetString(
20+
content,
21+
index ?? 0,
22+
count ?? content.Length
23+
);
24+
}
25+
26+
/// <summary>
27+
/// 二进制内容转 UTF32 字符串
28+
/// </summary>
29+
/// <param name="content">字节数组</param>
30+
/// <param name="index">内容起始下标</param>
31+
/// <param name="count">内容长度</param>
32+
/// <returns>UTF32 字符串</returns>
33+
public static string ToUTF32(this byte[] content, int? index = null, int? count = null)
34+
{
35+
if (index is null || count is null)
36+
return Encoding.UTF32.GetString(content);
37+
else
38+
return Encoding.UTF32.GetString(
39+
content,
40+
index ?? 0,
41+
count ?? content.Length
42+
);
43+
}
44+
45+
/// <summary>
46+
/// 二进制内容转 Unicode 字符串
47+
/// </summary>
48+
/// <param name="content">字节数组</param>
49+
/// <param name="index">内容起始下标</param>
50+
/// <param name="count">内容长度</param>
51+
/// <returns>Unicode 字符串</returns>
52+
public static string ToUnicode(this byte[] content, int? index = null, int? count = null)
53+
{
54+
if (index is null || count is null)
55+
return Encoding.Unicode.GetString(content);
56+
else
57+
return Encoding.Unicode.GetString(
58+
content,
59+
index ?? 0,
60+
count ?? content.Length
61+
);
62+
}
63+
64+
/// <summary>
65+
/// 二进制内容转 ASCII 字符串
66+
/// </summary>
67+
/// <param name="content">字节数组</param>
68+
/// <param name="index">内容起始下标</param>
69+
/// <param name="count">内容长度</param>
70+
/// <returns>ASCII 字符串</returns>
71+
public static string ToASCII(this byte[] content, int? index = null, int? count = null)
72+
{
73+
if (index is null || count is null)
74+
return Encoding.ASCII.GetString(content);
75+
else
76+
return Encoding.ASCII.GetString(
77+
content,
78+
index ?? 0,
79+
count ?? content.Length
80+
);
81+
}
82+
}

0 commit comments

Comments
 (0)