我使用以下代码来阅读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) 目前我正在使用此代码将字符串转换为字节数组:
var tempByte = System.Text.Encoding.UTF8.GetBytes(tempText);
Run Code Online (Sandbox Code Playgroud)
我经常在我的应用程序中调用此行,我真的想使用更快的行.如何将字符串转换为字节数组比默认的GetBytes方法更快?也许有一个不安全的代码?
随着各种渠道的帮助下,我已经写了一些SwapBytes在我的二进制读取类的方法,在交换端ushort,uint以及ulong所有使用所有原始C#,无需任何按位运算unsafe的代码.
public ushort SwapBytes(ushort x)
{
return (ushort)((ushort)((x & 0xff) << 8) | ((x >> 8) & 0xff));
}
public uint SwapBytes(uint x)
{
return ((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24);
}
public ulong SwapBytes(ulong value)
{
ulong uvalue = value;
ulong swapped =
((0x00000000000000FF) & (uvalue >> 56)
| (0x000000000000FF00) & (uvalue …Run Code Online (Sandbox Code Playgroud)