string和byte[]的转换 (C#)

string和byte[]的转换 (C#)

 string类型转成byte[]:

 

byte[] byteArray = System.Text.Encoding.Default.GetBytes ( str );

反过来,byte[]转成string:

 

string str = System.Text.Encoding.Default.GetString ( byteArray );


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

 

 

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

 

byte[] byteArray = System.Text.Encoding.ASCII.GetBytes ( str );

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

 

string str = System.Text.Encoding.ASCII.GetString ( byteArray );

 

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

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

 

        public static string ToHexString ( byte[] bytes ) // 0xae00cf => "AE00CF "
        {
            
string hexString = string.Empty;
            
if ( bytes != null )
            
{
                StringBuilder strB 
= new StringBuilder ();

                
for ( int i = 0; i < bytes.Length; i++ )
                
{
                    strB.Append ( bytes[i].ToString ( 
"X2" ) );
                }

                hexString 
= strB.ToString ();
            }

            
return hexString;
        }


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

 

        public static byte[] GetBytes(string hexString, out int discarded)
        
{
            discarded 
= 0;
            
string newString = "";
            
char c;
            
// remove all none A-F, 0-9, characters
            for (int i=0; i<hexString.Length; i++)
            
{
                c 
= hexString[i];
                
if (IsHexDigit(c))
                    newString 
+= c;
                
else
                    discarded
++;
            }

            
// if odd number of characters, discard last character
            if (newString.Length % 2 != 0)
            
{
                discarded
++;
                newString 
= newString.Substring(0, newString.Length-1);
            }


            
int byteLength = newString.Length / 2;
            
byte[] bytes = new byte[byteLength];
            
string hex;
            
int j = 0;
            
for (int i=0; i<bytes.Length; i++)
            
{
                hex 
= new String(new Char[] {newString[j], newString[j+1]});
                bytes[i] 
= HexToByte(hex);
                j 
= j+2;
            }

            
return bytes;
        }

 

0
0
(请您对文章做出评价)
« 上一篇:软件维护的噩梦
» 下一篇:记录log中的16进制和ASCII码字符输出
posted @ 2008-04-09 10:40 Mainz 阅读(7880) 评论(7)  编辑 收藏 网摘 所属分类: C#

发表评论
  回复  引用  查看    
#1楼2008-04-09 12:35 | 李战      
路过,支持
  回复  引用    
#2楼 211.100.22.* 2008-07-31 11:44 | 上帝禁区[未注册用户]
16进制格式的string 转成byte[]一句话就够了.同学.
BitConverter.GetBytes((Convert.ToInt32(byteArray,16)))

  回复  引用  查看    
#3楼[楼主]2008-07-31 12:24 | Mainz      
@上帝禁区
不一样的,
byte[] rettt = BitConverter.GetBytes ( ( Convert.ToInt32 ( "3031", 16 ) ) );
得到的是byte[]{0x31,0x30, 0x00, 0x00};

  回复  引用    
#4楼 123.112.174.* 2008-08-24 18:09 | 快乐的老K[未注册用户]
好文章 正好用到!

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;
}

  回复  引用    
#5楼 120.8.166.* 2009-01-23 09:57 | hs518[未注册用户]
4楼的太好了,解决我的大问题了。
  回复  引用  查看    
#6楼[楼主]2009-02-03 17:52 | Mainz      
@快乐的老K
你的函数可以完全替换 public static byte[] GetBytes(string hexString, out int discarded)这个函数。谢谢补充。

  回复  引用    
#7楼 125.66.33.* 2009-03-17 10:56 | yw8888[未注册用户]
很好,但HexToByte函数在处理 “0”到"111"时结果不正确,只有“10” ,“11”两项正确
posted @ 2010-02-25 09:48  网络金领  阅读(400)  评论(0编辑  收藏  举报