string类型转成byte[]:

 

string和byte[]的转换 (C#)byte[] byteArray = System.Text.Encoding.Default.GetBytes ( str );

反过来,byte[]转成string:

 

string和byte[]的转换 (C#)string str = System.Text.Encoding.Default.GetString ( byteArray );


其它编码方式的,如System.Text.UTF8Encoding,System.Text.UnicodeEncoding class等;例如:

 

 

string类型转成ASCII byte[]:("01" 转成 byte[] = new byte[]{ 0x30, 0x31})

 

string和byte[]的转换 (C#)byte[] byteArray = System.Text.Encoding.ASCII.GetBytes ( str );

ASCII byte[] 转成string:(byte[] = new byte[]{ 0x30, 0x31} 转成 "01")

 

string和byte[]的转换 (C#)string str = System.Text.Encoding.ASCII.GetString ( byteArray );

 

有时候还有这样一些需求:

byte[] 转成原16进制格式的string,例如0xae00cf, 转换成 "ae00cf";new byte[]{ 0x30, 0x31}转成"3031":

 

string和byte[]的转换 (C#)        public static string ToHexString ( byte[] bytes ) // 0xae00cf => "AE00CF "
        }


反过来,16进制格式的string 转成byte[],例如, "ae00cf"转换成0xae00cf,长度缩减一半;"3031" 转成new byte[]{ 0x30, 0x31}:

 

string和byte[]的转换 (C#)        public static byte[] GetBytes(string hexString, out int discarded)
        }

 

0
0
(请您对文章做出评价)
posted @ 2008-04-09 10:40 Mainz 阅读(7880) 评论(7)  编辑 收藏 网摘 所属分类: C#
string和byte[]的转换 (C#)

发表评论
  回复  引用  查看    
#1楼     
路过,支持
16进制格式的string 转成byte[]一句话就够了.同学.
BitConverter.GetBytes((Convert.ToInt32(byteArray,16)))

  回复  引用  查看    
#3楼     
得到的是byte[]{0x31,0x30, 0x00, 0x00};
好文章 正好用到!

HexToByte 这个函数没有给出,这是我在微软网站上找的,可以直接替换楼主最后那段操作。

private static byte[] HexToByte(string hexString)
{
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}

4楼的太好了,解决我的大问题了。
  回复  引用  查看    
#6楼     
@快乐的老K
你的函数可以完全替换 public static byte[] GetBytes(string hexString, out int discarded)这个函数。谢谢补充。

相关文章: