温馨提示×

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

c#
小樊
82
2024-09-11 01:47:27
栏目: 编程语言

在C#中,可以使用System.IO.MemoryStreamSystem.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,以便从头开始读取数据。最后,我们使用BinaryReaderMemoryStream中读取数据,并将读取到的数据输出到控制台。

0