C#中string與byte[]的轉換幫助類-.NET教程,C#語言
2024-09-07 17:05:19
供稿:網友
主要實現了以下的函數
代碼中出現的sidle是我的網名。
/**//*
* @author wuerping
* @version 1.0
* @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是 31
/// asc: ascii
/// uni: unicode
/// </summary>
public sealed class strhelper
{
hex與hexbin的轉換#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);
}
}
}