C# C语言中读取大端数据的有效方法#
我使用下面的代码使用C# C语言中读取大端数据的有效方法#,c#,endianness,binaryreader,C#,Endianness,Binaryreader,我使用下面的代码使用binarydreader读取BigEndian信息,但我不确定这是否是有效的方法。有没有更好的解决办法 这是我的密码: // 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
binarydreader
读取BigEndian信息,但我不确定这是否是有效的方法。有没有更好的解决办法
这是我的密码:
// 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);
你可以用,但我不知道它是否真的更有效。您必须对其进行分析。
位转换器。ToInt32
首先不是很快。我只想用
public static int ToInt32BigEndian(byte[] buf, int i)
{
return (buf[i]<<24) | (buf[i+1]<<16) | (buf[i+2]<<8) | buf[i+3];
}
公共静态整数到32bigendian(字节[]buf,整数i)
{
返回(buf[i]从2019年开始(事实上,从.net core 2.1开始),现在有
byte[]缓冲区=。。。;
ReadInt32BigEndian(buffer.AsSpan());
谢谢这很有趣,但为了确保我的想法正确,你能解释一下我们如何读取超过4个字节。只需调用长度更大的ReadBytes
,然后使用不同的I
读取数组中不同位置的整数。但这是一个优化,你应该在基准测试后进行。耶s、 我在我的一些项目中使用过类似的东西(虽然不是在C#中),但我希望BinaryReader/Writer内置endian控件,这会使它更简单。