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

时间:2021-06-08 22:47:33

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数组,然后再使用前面提到的转换方法转换为对应的字符。