Class - Convert String To Number


  1 
  2 using System; 
  3 using System.Text; 
  4 namespace SidleHelper 
  5 
  6 /// <summary> 
  7 /// Summary description for StrHelper. 
  8 /// 命名缩写: 
  9 /// Str: unicode string 
 10 /// Arr: unicode array 
 11 /// Hex: 二进制数据 
 12 /// Hexbin: 二进制数据用ASCII字符表示 例 字符'1'的hex是0x31表示为hexbin是 '3''1' 
 13 /// Asc: ASCII 
 14 /// Uni: UNICODE 
 15 /// </summary> 
 16 public sealed class StrHelper 
 17 
 18 #region Hex与Hexbin的转换 
 19 public static void Hexbin2Hex(byte[] bHexbin, byte[] bHex, int nLen) 
 20 
 21 for(int i=0; i<nLen/2; i++
 22 
 23 if(bHexbin[2*i] <0x41
 24 
 25 bHex[i] = Convert.ToByte(((bHexbin[2*i] - 0x30)<<4& 0xf0); 
 26 
 27 else 
 28 
 29 bHex[i] = Convert.ToByte(((bHexbin[2*i] - 0x37)<<4& 0xf0); 
 30 
 31 
 32 if(bHexbin[2*i+1<0x41
 33 
 34 bHex[i] |= Convert.ToByte((bHexbin[2*i+1- 0x30& 0x0f); 
 35 
 36 else 
 37 
 38 bHex[i] |= Convert.ToByte((bHexbin[2*i+1- 0x37& 0x0f); 
 39 
 40 
 41 
 42 public static byte[] Hexbin2Hex(byte[] bHexbin, int nLen) 
 43 
 44 if(nLen%2 !=0
 45 return null
 46 byte[] bHex = new byte[nLen/2]; 
 47 Hexbin2Hex(bHexbin, bHex, nLen); 
 48 return bHex; 
 49 
 50 public static void Hex2Hexbin(byte[] bHex, byte[] bHexbin, int nLen) 
 51 
 52 byte c; 
 53 for(int i=0;i<nLen;i++
 54 
 55 = Convert.ToByte((bHex[i]>>4& 0x0f); 
 56 if(c < 0x0a
 57 
 58 bHexbin[2*i] = Convert.ToByte(c + 0x30); 
 59 
 60 else 
 61 
 62 bHexbin[2*i] = Convert.ToByte(c + 0x37); 
 63 
 64 = Convert.ToByte(bHex[i]&0x0f); 
 65 if(c < 0x0a
 66 
 67 bHexbin[2*i+1= Convert.ToByte(c + 0x30); 
 68 
 69 else 
 70 
 71 bHexbin[2*i+1= Convert.ToByte(c + 0x37); 
 72 
 73 
 74 
 75 public static byte[] Hex2Hexbin(byte[] bHex, int nLen) 
 76 
 77 byte[] bHexbin = new byte[nLen*2]; 
 78 Hex2Hexbin(bHex, bHexbin, nLen); 
 79 return bHexbin; 
 80 
 81 #endregion 
 82 
 83 #region 数组和字符串之间的转化 
 84 public static byte[] Str2Arr(String s) 
 85 
 86 return (new UnicodeEncoding()).GetBytes(s); 
 87 
 88 public static string Arr2Str(byte[] buffer) 
 89 
 90 return (new UnicodeEncoding()).GetString(buffer, 0, buffer.Length); 
 91 
 92 
 93 public static byte[] Str2AscArr(String s) 
 94 
 95 return System.Text.UnicodeEncoding.Convert(System.Text.Encoding.Unicode, 
 96 System.Text.Encoding.ASCII, 
 97 Str2Arr(s)); 
 98 
 99 
100 public static byte[] Str2HexAscArr(String s) 
101 
102 byte[] hex = Str2AscArr(s); 
103 byte[] hexbin = Hex2Hexbin(hex, hex.Length); 
104 return hexbin; 
105 
106 public static string AscArr2Str(byte[] b) 
107 
108 return System.Text.UnicodeEncoding.Unicode.GetString( 
109 System.Text.ASCIIEncoding.Convert(System.Text.Encoding.ASCII, 
110 System.Text.Encoding.Unicode, 
111 b) 
112 ); 
113 
114 
115 public static string HexAscArr2Str(byte[] buffer) 
116 
117 byte[] b = Hex2Hexbin(buffer, buffer.Length); 
118 return AscArr2Str(b); 
119 
120 #endregion 
121 
122 

posted on 2009-06-08 08:24  Createk  阅读(706)  评论(0编辑  收藏  举报

导航