在写C#程序时,string和byte[]之间的转换比较烦,在移植一些老程序时感觉很不好。我在C#中使用DES和TripleDES时移植一块老代码时也遇到了同样的情况。为了下次不为同样的事情烦恼,就写了下面的帮助类。
主要实现了以下的函数

代码中出现的Sidle是我的网名。
/*
- @Author WuErPing
- @Version 1.0
- @Date 2004/11/30
- @Description:
*/
using System;
using System.Text;
namespace SidleHelper
{
///
1<summary>
2/// Summary description for StrHelper.
3/// 命名缩写:
4/// Str: unicode string
5/// Arr: unicode array
6/// Hex: 二进制数据
7/// Hexbin: 二进制数据用ASCII字符表示 例 字符'1'的hex是0x31表示为hexbin是 '3''1'
8/// Asc: ASCII
9/// Uni: UNICODE
10/// </summary>
public sealed class StrHelper
{
#region Hex与Hexbin的转换
public static void Hexbin2Hex(byte[] bHexbin, byte[] bHex, int nLen)
{
for(int i=0; i
1<nlen !="0)" &="" -="" 0x0f);="" 0x30)="" 0x30)<<4)="" 0x37)="" 0x37)<<4)="" 0xf0);="" 2;="" 2];="" <0x41)="" bhex="new" bhex,="" bhex;="" bhex[i]="" bhexbin,="" byte="" byte[]="" byte[nlen="" c="Convert.ToByte((bHex[i]" c;="" else="" for(int="" hex2hexbin(byte[]="" hexbin2hex(bhexbin,="" hexbin2hex(byte[]="" i="0;i<nLen;i++)" i++)="" if(bhexbin[2*i+1]="" if(bhexbin[2*i]="" if(nlen%2="" int="" nlen)="" nlen);="" null;="" public="" return="" static="" void="" {="" |="Convert.ToByte((bHexbin[2*i+1]" }="">>4) & 0x0f);
2if(c < 0x0a)
3{
4bHexbin[2*i] = Convert.ToByte(c + 0x30);
5}
6else
7{
8bHexbin[2*i] = Convert.ToByte(c + 0x37);
9}
10c = Convert.ToByte(bHex[i]&0x0f);
11if(c < 0x0a)
12{
13bHexbin[2*i+1] = Convert.ToByte(c + 0x30);
14}
15else
16{
17bHexbin[2*i+1] = Convert.ToByte(c + 0x37);
18}
19}
20}
21public static byte[] Hex2Hexbin(byte[] bHex, int nLen)
22{
23byte[] bHexbin = new byte[nLen*2];
24Hex2Hexbin(bHex, bHexbin, nLen);
25return bHexbin;
26}
27#endregion
28
29#region 数组和字符串之间的转化
30public static byte[] Str2Arr(String s)
31{
32return (new UnicodeEncoding()).GetBytes(s);
33}
34public static string Arr2Str(byte[] buffer)
35{
36return (new UnicodeEncoding()).GetString(buffer, 0, buffer.Length);
37}
38
39public static byte[] Str2AscArr(String s)
40{
41return System.Text.UnicodeEncoding.Convert(System.Text.Encoding.Unicode,
42System.Text.Encoding.ASCII,
43Str2Arr(s));
44}
45
46public static byte[] Str2HexAscArr(String s)
47{
48byte[] hex = Str2AscArr(s);
49byte[] hexbin = Hex2Hexbin(hex, hex.Length);
50return hexbin;
51}
52public static string AscArr2Str(byte[] b)
53{
54return System.Text.UnicodeEncoding.Unicode.GetString(
55System.Text.ASCIIEncoding.Convert(System.Text.Encoding.ASCII,
56System.Text.Encoding.Unicode,
57b)
58);
59}
60
61public static string HexAscArr2Str(byte[] buffer)
62{
63byte[] b = Hex2Hexbin(buffer, buffer.Length);
64return AscArr2Str(b);
65}
66#endregion
67}
68}</nlen>