C#类型转换、进制转换
string转byte[]:
byte[] byteArray = System.Text.Encoding.Default.GetBytes ( str );
byte[]转string:
string str = System.Text.Encoding.Default.GetString ( byteArray );
foreach (byte b in buf)
{
strBuilderSB.Append(b.ToString("X2") + " ");
}
string转ASCII byte[]:
byte[] byteArray = System.Text.Encoding.ASCII.GetBytes ( str );
ASCII byte[]转string:
string str = System.Text.Encoding.ASCII.GetString ( byteArray );
//十进制转二进制
Console.WriteLine(Convert.ToString(69, 2));
//十进制转八进制
Console.WriteLine(Convert.ToString(69, 8));
//十进制转十六进制
Console.WriteLine(Convert.ToString(69, 16));
int a = 10; a.ToString("x4");// x表示转换的格式是16进制,4表示填充位为4位,不够4位补0。
//二进制转十进制
Console.WriteLine(Convert.ToInt32(”100111101″, 2));
//八进制转十进制
Console.WriteLine(Convert.ToInt32(”76″, 8));
//十六进制转十进制
Console.WriteLine(Convert.ToInt32(”FF”, 16));
//byte[]数组转16进制
public string ByteArrayToHexString(byte[] data) { StringBuilder sb = new StringBuilder(); foreach(byte b in data) { sb.Append(((int)b).ToString("X2")); } return sb.ToString().ToUpper(); }
// 16进制转byte[]数组
private byte[] HexStrTobyte(string hexString) { hexString = hexString.Replace(" ", ""); if ((hexString.Length % 2) != 0) 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).Trim(), 16); return returnBytes; }
//byte[]转ASCII字符串
Encoding.ASCII.GetString(buffer,0,count); Encoding.GetEncoding("GB2312").GetString(data);