阅读在C#大端数据有效的方法 [英] Efficient way to read big endian data in C#

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

问题描述

我用下面的代码中使用 BinaryReader 阅读大尾端信息,但我不知道如果是这样做的有效途径。 ?有没有更好的解决方案。



下面是我的代码:

  //一些代码来初始化流值
//设置长度值的大小的Int32
BinaryReader读卡器=新BinaryReader(流);
字节[]字节= reader.ReadBytes(长度);
Array.Reverse(字节);
INT结果= System.BitConverter.ToInt32(温度,0);


解决方案

BitConverter.ToInt32 不是很快摆在首位。我会简单地使用



 公共静态INT ToInt32BigEndian(字节[] buf中,int i)以
{
返回(BUF [1] - ;&下; 24)| (BUF第[i + 1];&下; 16)| (BUF第[i + 2]所述;&下; 8)|的buf [1 + 3];
}

您也可以考虑在同一时间读取超过4个字节。


I use the following code to read BigEndian information using BinaryReader but I'm not sure if it is the efficient way of doing it. Is there any better solution?

Here is my code:

// some code to initialize the stream value
// set the length value to the Int32 size
BinaryReader reader =new BinaryReader(stream);
byte[] bytes = reader.ReadBytes(length);
Array.Reverse(bytes);
int result = System.BitConverter.ToInt32(temp, 0);

解决方案

BitConverter.ToInt32 isn't very fast in the first place. I'd simply use

public static int ToInt32BigEndian(byte[] buf, int i)
{
  return (buf[i]<<24) | (buf[i+1]<<16) | (buf[i+2]<<8) | buf[i+3];
}

You could also consider reading more than 4 bytes at a time.

这篇关于阅读在C#大端数据有效的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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