天天看点

byte数组操作

//1.字节转换
float m = 5f;
var btValue = BitConverter.GetBytes(m).Reverse().ToArray();
//转为原值字符串
string m1 = System.Text.Encoding.Default.GetString(btValue);

//2.byte 数组合并
byte[] data = new byte[10];
byte[] counts = new byte[3];
byte[] ndata = new byte[data.Length + counts.Length];
//将data复制到ndata
data.CopyTo(ndata, 0);//从ndata的下标为0的地方开始存放
counts.CopyTo(ndata, data.Length);

//3.string和byte[]转换
string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//string转byte[]:
byte[] byteArray1 = System.Text.Encoding.Default.GetBytes(str);
//byte[] 转string:
string str1 = System.Text.Encoding.Default.GetString(byteArray1);
//string转ASCII byte[]:
byte[] byteArray2 = System.Text.Encoding.ASCII.GetBytes(str);
//ASCII byte[] 转string:
string str2 = System.Text.Encoding.ASCII.GetString(byteArray2);

//4.字符串拆分数组
string a = "A|B|C|D";
string[] a1 = a.Split('|');

//5.Int转为16进制
int b = 58;
byte b1 = Convert.ToByte(b);

//6.byte数组截取
byte[] test = byteArray2.Skip(4).Take(3).ToArray();//从下标4开始截取长度3

//7.List转为Byte[]
List<byte> frameBytes = new List<byte>();
frameBytes.Add(0x9E);
byte[] phoneNumByte = new byte[] { 0x01, 0x03, 0x05, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00 };//定义一个数组        
for (int i = 0; i < phoneNumByte.Length; i++)
{
    frameBytes.Add(phoneNumByte[i]);
}
frameBytes = frameBytes.Concat(byteArray2).ToList<byte>();//两个list合并
//list转byte[]
byte[] transByte = frameBytes.ToArray();
//byte[]转list
List<byte> lb =transByte.ToList();

           

本文来自博客园,作者:農碼一生,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/15620987.html

技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正! 个人开源代码链接: GitHub:

https://github.com/ITMingliang

Gitee:

https://gitee.com/mingliang_it

GitLab:

https://gitlab.com/ITMingliang

进开发学习交流群:
byte数组操作