我使用以下代码来阅读BigEndian信息,BinaryReader但我不确定它是否是有效的方法.有没有更好的解决方案?
这是我的代码:
// 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);
Run Code Online (Sandbox Code Playgroud) 2nd edit:
I think my original test script has an issue, the 10000000 times loop is, in fact, dealing with the same memory location of an array, which makes the unsafe version (provided by Marc here) much faster than bitwise version. I wrote another test script, I noticed that bitwise and unsafe offers almost the same performance.
loop for 10,000,000 times
Bitwise: 4218484; UnsafeRaw: 4101719
0.0284673328426447545529081831 (~2% Difference)
here is the code:
unsafe class UnsafeRaw
{
public static short …Run Code Online (Sandbox Code Playgroud)