01,C# string类型转成byte[]:
Byte[] byteArray = System.Text.Encoding.Default.GetBytes ( str );
02, C# byte[]转成string:
stringstr = System.Text.Encoding.Default.GetString ( byteArray );
03,C# string类型转成ASCIIbyte[]:
("01"转成byte[] =newbyte[]{0x30,0x31})
byte[] byteArray = System.Text.Encoding.ASCII.GetBytes ( str );
04,C# ASCIIbyte[]转成string:
(byte[] = new byte[]{ 0x30, 0x31} 转成"01")
string str = System.Text.Encoding.ASCII.GetString ( byteArray );
05, C# byte[]转16进制格式string:
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;
}
C# 常见的字节数组 byte[]截取
C# byte[]数组截取:
byte[] data= new byte[]{1,2,3,4,5,6,7,8,9};
截取2位:BitConverter.ToInt16(data,3);//3表示从第三个位置开始
截取4位:BitConverter.ToInt32(data,3);
截取8位:BitConverter.ToInt64(data,3);
如果截取的数量不规则:data.Skip(5).Take(3).ToArray(); //表示从第五个位置截取三个字节
data.Skip(4).ToArray(); //表示从第四个位置截取到最后
C# byte[]数组复制
(1)
byte[] data = new byte[]{0,1,2,3,4,5,6,7,8,9};
byte[] data1 = new byte[data.length];
for(int i=0;i<data1.length;i++){
data1[i] = data[i];
}
(2)全部复制
byte[] data = new byte[]{0,1,2,3,4,5,6,7,8,9};
byte[] data1 = new byte[data.length];
Array.Copy(data,data1,data.length);//源数据data,目标数据data1,复制长度data.length
(3)全部复制
byte[] data = new byte[]{0,1,2,3,4,5,6,7,8,9};
byte[] data1;
data1 = (byte[])data .Clone();
(4)深度复制
byte[] srcArray = new byte[] { 0x01, 0x02, 0x03, 0x04 };
byte[] dstArray = new byte[srcArray.Length];
Buffer.BlockCopy(srcArray, 0, dstArray, 0, srcArray.Length);//源数据srcArray , 起始位置0,目标数组dstArray ,开始位置0, 多少长度 srcArray.Length
C# byte[]数组删除
byte[] data = new byte[]{0,1,2,3,4,5,6,7,8,9};
(1)删除指定位置数量的数据
Array.Clear(data,0,5); //data 从起始位置0, 删除5个位置
(2)删除指定的数据--返回byte[] 空间减少
///
/// 去掉byte[] 中特定的byte
///
/// 需要处理的byte[]
/// byte[] 中需要除去的特定 byte (此处: byte cut = 0x00 ;)
///
public static byte[] ByteCut(byte[] b, byte cut)
{
var list = new List();
list.AddRange(b);
for (var i = list.Count - 1; i >= 0; i--)
{
if (list[i] == cut)
list.RemoveAt(i);
}
var lastbyte = new byte[list.Count];
for (var i = 0; i < list.Count; i++)
{
lastbyte[i] = list[i];
}
return lastbyte;
}
(3)清空byte[]
byte[] data = new byte[50];
data = new byte[50];//新new 出来则原来空间数据清除
标签:string,C#,list,new,Byte,data,byte From: https://www.cnblogs.com/lrzy/p/17305096.html