Net Core教程

C# 通过MemoryStream,BinaryWriter,BinaryReader读写字节数据

本文主要是介绍C# 通过MemoryStream,BinaryWriter,BinaryReader读写字节数据,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

不用自己再去写各种数据类型转字节数组的方法了,用起来很方便,不过如果要和第三方程序通讯的话,需要搞清楚BinaryWriter和BinaryReader是怎么实现的,让下位机按照BinaryWriter和BinaryReader的方式传输数据,而且ms.GetBuffer()得到的数据貌似是直接返回的内部字节数组,数组的长度可能会严重大于实际数据的长度

using System;
using System.IO;

namespace ConsoleApp {
    class Program {
        static void Main(string[] args) {
            Model model = new Model {
                CmdID = 0x01,
                UserID = 9999,
                Name = "张三丰"
            };
            byte[] byteArray = Write(model);
            Model readData = Read(byteArray);
            Console.ReadKey();
        }
        class Model {
            public byte CmdID { get; set; }
            public int UserID { get; set; }
            public string Name { get; set; }
        }
        /// <summary>
        /// 将数据写入到字节数组中
        /// </summary>
        static byte[] Write(Model data) {
            MemoryStream ms = new MemoryStream();
            BinaryWriter bw = new BinaryWriter(ms);
            bw.Write(data.CmdID);  //写数据
            bw.Write(data.UserID);
            bw.Write(data.Name);
            return ms.GetBuffer();
        }
        /// <summary>
        /// 从字节数组中读取数
        /// </summary> 
        static Model Read(byte[] byteArray) {
            MemoryStream ms = new MemoryStream(byteArray);
            BinaryReader br = new BinaryReader(ms);
            return new Model {
                CmdID = br.ReadByte(),  //读数据
                UserID = br.ReadInt32(),
                Name = br.ReadString()
            };
        }
    }
}

 

这篇关于C# 通过MemoryStream,BinaryWriter,BinaryReader读写字节数据的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!