新客网WWW.XKER.COM:致力做中国最专业的网络学院!
学院: 操作系统 - 网络应用 - 服务器 - 网络安全 - 工具软件 - 办公软件 - Web开发 - 数据库 - 网页设计 - 图形图像 - 媒体动画 - 硬件学堂 - 存储频道 - QQ专区
您的位置:首页 > 软件开发 > .Net开发 > Asp.net教程 > 正文:C#中string与byte[]的转换帮助类

C#中string与byte[]的转换帮助类

新客网 XKER.COM 2004-12-02 来源: 收藏本文
在写C#程序时,string和byte[]之间的转换比较烦,在移植一些老程序时感觉很不好。我在C#中使用DES和TripleDES时移植一块老代码时也遇到了同样的情况。为了下次不为同样的事情烦恼,就写了下面的帮助类。
主要实现了以下的函数


代码中出现的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是 '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
}
}

收藏】 【评论】 【推荐】 【投稿】 【打印】 【关闭
发表评论
要记得去论坛讨论,点击注册新会员匿名评论
评论内容:不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
阅读排行
随机推荐
实用信息推荐