C#读取字节数组 [英] C# Reading Byte Array

查看:120
本文介绍了C#读取字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我正在构建服务器<->客户端应用程序.

Okay so I am building server <-> client application.

基本上,服务器接收到一个包含报头[2bytes],密钥[2bytes]和数据的数据包

Basically server receives a packet that contains header[2bytes], cryptokeys[2bytes],and data

我正在考虑构建类以将整个数据包(byte [])加载到其中,然后使用内部类方法处理该数据包.现在到问题了.最好的方法是什么?我需要能够读取Int16 Int32 String(int lenght)并可能会浮动

I was thinking about building class to load whole packet (byte[]) into it and then process the packet with inside class methods. Now to the question. What would be best approach to this? I need to be able to read Int16 Int32 String(int lenght) and probably float

Kinda类似于binaryreader,但以byte []作为输入

Kinda like binaryreader but for byte[] as an input

推荐答案

我会说BinaryReader是您的最佳选择.根据过去的经验,有时需要从BinaryReader继承.一个主要的例子是,由于BinaryReader读取以长度为前缀的字符串,因此您需要读取以null结尾的字符串.或者,您可以编写自己的类,但最终将提供与BinaryReader相同的功能.

I would say BinaryReader is your best choice. From past experience there are times where you need to inherit from BinaryReader. A primary example is when you need to read a null-terminated string because BinaryReader reads length-prefixed strings. Or you can write your own class, but you will end up providing the same functionality as BinaryReader.

最后,我可能只会创建自己的课程.这样,如果您需要更改提取数据的方式,则只需编辑您的班级即可.如果您使用BinaryReader编写整个项目,并意识到需要添加功能,则会被拧紧.

In the end I would probably just create my own class. That way if you need to make changes on how you want to extract the data, you can just edit your class. If you write the entire project with BinaryReader and realize you need to add functionality you will be screwed.

public class MyBinaryReader : BinaryReader
{
    public MyBinaryReader(byte[] input) : base(new MemoryStream(input))
    {
    }

    public override string ReadString()
    {
         // read null-terminated string
    }
}

这篇关于C#读取字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆