tijian_jichuang/Code/SmartUpdater/Bytes.cs
2025-02-20 11:54:48 +08:00

63 lines
2.1 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Text;
namespace EAS.Distributed
{
static class Bytes
{
/// <summary>
/// 将指定的字节数组转换为HEX字符串。
/// </summary>
/// <param name="buffer">要转换的字节数组。</param>
/// <returns>返回已经转换的字节数组字符串。</returns>
public static string ToHex(this byte[] buffer)
{
if (buffer == null)
return null;
if (buffer.Length == 0)
return string.Empty;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < buffer.Length; i++)
{
sb.Append(buffer[i].ToString("X2"));
}
return sb.ToString();
}
/// <summary>
/// 将格式为“XXXX”的字符串。其中“xx”为每一个字节的十六进制表示转换为相应的字节数组。
/// </summary>
/// <param name="s">要转换的字符串。</param>
/// <returns>返回转换后的字节数组。</returns>
/// <exception cref="ArgumentNullException">s 为空引用。</exception>
/// <exception cref="ArgumentException">字符串 s 格式无效。</exception>
/// <remarks>如果 s 为空字符串,则返回长度为 0 的字节数组。</remarks>
public static byte[] FromHex(this string s)
{
if (s == null)
throw new ArgumentNullException("s", "要转换的字符串不能是空引用。");
if (s.Trim() == string.Empty)
return new byte[0];
if (s.Length % 2 != 0)
throw new ArgumentNullException("s", "要转换的字符串长度必须为2的整数倍。");
byte[] buffer = new byte[s.Length / 2];
for (int i = 0; i < buffer.Length; i++)
{
string Text = s.Substring(i * 2, 2);
try
{
buffer[i] = byte.Parse(Text, System.Globalization.NumberStyles.AllowHexSpecifier);
}
catch (System.FormatException exc)
{
throw new System.ArgumentException("无效的字节字符串格式。", "s", exc);
}
}
return buffer;
}
}
}