如何阅读内存流中的短片? [英] How to read short in memorystream?

查看:90
本文介绍了如何阅读内存流中的短片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我尝试读取十六进制的2字节标题,如

Hi im try to read 2 bytes header in hex like this

52 01







but

MemoryStream



只允许使用ReadByte()。



这是我的代码




just allow ReadByte() only.

this is my code

ushort size = BitConverter.ToUInt16(new byte[] { (byte)ReceiveStream.ReadByte(), (byte)ReceiveStream.ReadByte() }, 0);
                ReceiveStream.Position -= 2;

                while (size > 0 && size <= (ReceiveStream.Length - ReceiveStream.Position))
                {
                    //Log.Debug("Read: " + size + "-byte packet.");

                    // Read Packet Data including length
                    byte[] data = new byte[size];
                    ReceiveStream.Read(data, 0, size);

                    // Process packet.
                    MemoryStream stream = new MemoryStream(data, 2, data.Length - 2, false);

                    int opcode = stream.ReadByte();//TODO i want to read 2 bytes
                    
					//other code call the opcode value
                }







这是我的问题:




this is my problem:

int opcode = stream.ReadByte();





操作码值必须是152,就像我给出的标题值一样。但是我的代码只读了52。



我需要一些帮助xD



我尝试过:





the opcode value must be "152" like the header value i've give. But my code just read "52" only.

I need some help xD

What I have tried:

ushort size = BitConverter.ToUInt16(new byte[] { (byte)ReceiveStream.ReadByte(), (byte)ReceiveStream.ReadByte() }, 0);
                ReceiveStream.Position -= 2;

                while (size > 0 && size <= (ReceiveStream.Length - ReceiveStream.Position))
                {
                    //Log.Debug("Read: " + size + "-byte packet.");

                    // Read Packet Data including length
                    byte[] data = new byte[size];
                    ReceiveStream.Read(data, 0, size);

                    // Process packet.
                    MemoryStream stream = new MemoryStream(data, 2, data.Length - 2, false);

                    int opcode = stream.ReadByte();//TODO i want to read 2 bytes
                    
					//other code call the opcode value
                }

推荐答案

从流中读取两个字节并进行转换他们自己知道字节顺序应该是什么:

Read two bytes from the stream and either convert them yourself as you know what the byte order should be:
byte a = 52;
byte b = 1;
ushort result = (ushort)((int) a | (b << 8));


您可以读取2个字节并自行进行位移或使用 BinaryReader BinaryReader类(System.IO) [ ^ ]
You can read 2 bytes and do the bit shifting yourself or use BinaryReader : BinaryReader Class (System.IO)[^]


这篇关于如何阅读内存流中的短片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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