C#中string与byte[]的转换帮助类
* @Date 2004/11/30
* @Description:
*/
using System;
using System.Text;
namespace SidleHelper
{
/// <summary>
/// Summary description for StrHelper.
/// 命名缩写:
/// Str: unicode string
/// Arr: unicode array
/// Hex: 二进制数据
/// Hexbin: 二进制数据用ASCII字符表示 例 字符'1'的hex是0x31表示为hexbin是 '3''1'
/// Asc: ASCII
/// Uni: UNICODE
/// </summary>
public sealed class StrHelper
{
#region Hex与Hexbin的转换
public static void Hexbin2Hex(byte[] bHexbin, byte[] bHex, int nLen)
{
for(int i=0; i<nLen/2; i++)
{
if(bHexbin[2*i] <0x41)
{
bHex[i] = Convert.ToByte(((bHexbin[2*i] - 0x30)<<4) & 0xf0);
}
else
{
bHex[i] = Convert.ToByte(((bHexbin[2*i] - 0x37)<<4) & 0xf0);
}
if(bHexbin[2*i+1] <0x41)
{
bHex[i] |= Convert.ToByte((bHexbin[2*i+1] - 0x30) & 0x0f);
}
else
{
bHex[i] |= Convert.ToByte((bHexbin[2*i+1] - 0x37) & 0x0f);
}
}
}
public static byte[] Hexbin2Hex(byte[] bHexbin, int nLen)
{
if(nLen%2 !=0)
return null;
byte[] bHex = new byte[nLen/2];
Hexbin2Hex(bHexbin, bHex, nLen);
return bHex;
}
public static void Hex2Hexbin(byte[] bHex, byte[] bHexbin, int nLen)
{
byte c;
for(int i=0;i<nLen;i++)
{
c = Convert.ToByte((bHex[i]>>4) & 0x0f);
if(c < 0x0a)
{
bHexbin[2*i] = Convert.ToByte(c + 0x30);
}
else
{
bHexbin[2*i] = Convert.ToByte(c + 0x37);
}
c = Convert.ToByte(bHex[i]&0x0f);
if(c < 0x0a)
{
bHexbin[2*i+1] = Convert.ToByte(c + 0x30);
}
else
{
bHexbin[2*i+1] = Convert.ToByte(c + 0x37);
}
}
}
public static byte[] Hex2Hexbin(byte[] bHex, int nLen)
{
byte[] bHexbin = new byte[nLen*2];
Hex2Hexbin(bHex, bHexbin, nLen);
return bHexbin;
}
#endregion
#region 数组和字符串之间的转化
public static byte[] Str2Arr(String s)
{
return (new UnicodeEncoding()).GetBytes(s);
}
public static string Arr2Str(byte[] buffer)
{
return (new UnicodeEncoding()).GetString(buffer, 0, buffer.Length);
}
public static byte[] Str2AscArr(String s)
{
return System.Text.UnicodeEncoding.Convert(System.Text.Encoding.Unicode,
System.Text.Encoding.ASCII,
Str2Arr(s));
}
public static byte[] Str2HexAscArr(String s)
{
byte[] hex = Str2AscArr(s);
byte[] hexbin = Hex2Hexbin(hex, hex.Length);
return hexbin;
}
public static string AscArr2Str(byte[] b)
{
return System.Text.UnicodeEncoding.Unicode.GetString(
System.Text.ASCIIEncoding.Convert(System.Text.Encoding.ASCII,
System.Text.Encoding.Unicode,
b)
);
}
public static string HexAscArr2Str(byte[] buffer)
{
byte[] b = Hex2Hexbin(buffer, buffer.Length);
return AscArr2Str(b);
}
#endregion
}
}
转:http://blog.csdn.net/21aspnet/archive/2007/03/24/1539999.aspx
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)