字节数组与字符串(字符数组)的转换操作

1、默认编码方式转换:

(1)string(char[])转换为byte[]

byte[] byteArr = System.Text.Encoding.Default.GetBytes(char[]);
byte[] byteArr = System.Text.Encoding.Default.GetBytes(string);
byte[] byteArr = System.Text.Encoding.Default.GetBytes(char[], startindex, count);
int count = System.Text.Encoding.Default.GetBytes(char * , count, byte*, startindex);
int count = System.Text.Encoding.Default.GetBytes(char[] , startindex, count, byte[], startindex);
int count = System.Text.Encoding.Default.GetBytes(s , startindex, count, byte[], startindex);

(2)byte[]转换为string(char[])

string str = System.Text.Encoding.Default.GetString ( byteArray );
string str = System.Text.Encoding.Default.GetString ( byteArray, startindex, count );
GetString方法和GetChar方法类似,后者将字节数组转换为对应的字符数组。


2、其他编码方式转换

将上述Default更换为ASCII、Unicode、UTF8、UTF7、UTF32等编码方式,然后调用对应方法就可以转换。

string str = "01";
byte[] byteArr = System.Text.Encoding.ASCI.GetBytes(str);
上述代码得到byteArr = {0x30, 0x31},这就是0和1的ASCI编码值。

byte[] byteArr = new byte[]{0x4e, 0x01};
string a = System.Text.Encoding.BigEndianUnicode.GetString(byteArr);
上述代码将unicode编码的第二个汉字“丁”解码赋值给变量a,“丁”的unicode码为\u4e01。

3、Byte[]中的十六进制转换为十六进制字符串

public static string ToHexString ( byte[] bytes ) 
{  
    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;  
}  

4、十六进制字符串转换为Byte数组

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;  
}  
对于获取到的使用unicode编码的网页或者其他文件,可以使用上述方法将加密后的unicode编码字符串转换为byte数组,然后再使用前面提到的转换方法转换为对应的字符。



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值