如何在C#中读取和写入ByteBuffer的数据

   2024-09-30 9520
核心提示:在C#中,可以使用System.IO.MemoryStream和System.IO.BinaryReader/System.IO.BinaryWriter来实现类似于Java中ByteBuffer的功能u

在C#中,可以使用System.IO.MemoryStream和System.IO.BinaryReader/System.IO.BinaryWriter来实现类似于Java中ByteBuffer的功能

using System;using System.IO;using System.Text;class Program{    static void Main()    {        // 创建一个MemoryStream实例,用于存储字节数据        using (MemoryStream memoryStream = new MemoryStream())        {            // 创建一个BinaryWriter实例,用于向MemoryStream中写入数据            using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8, true))            {                // 写入数据                binaryWriter.Write(123); // int                binaryWriter.Write(456.789f); // float                binaryWriter.Write("Hello, World!"); // string                // 将MemoryStream的位置重置为0,以便从头开始读取数据                memoryStream.Position = 0;                // 创建一个BinaryReader实例,用于从MemoryStream中读取数据                using (BinaryReader binaryReader = new BinaryReader(memoryStream, Encoding.UTF8, true))                {                    // 读取数据                    int intValue = binaryReader.ReadInt32();                    float floatValue = binaryReader.ReadSingle();                    string stringValue = binaryReader.ReadString();                    // 输出读取到的数据                    Console.WriteLine($"Int: {intValue}");                    Console.WriteLine($"Float: {floatValue}");                    Console.WriteLine($"String: {stringValue}");                }            }        }    }}

在这个示例中,我们首先创建了一个MemoryStream实例,然后使用BinaryWriter向其中写入了一个整数、一个浮点数和一个字符串。接着,我们将MemoryStream的位置重置为0,以便从头开始读取数据。最后,我们使用BinaryReader从MemoryStream中读取数据,并将读取到的数据输出到控制台。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号