gpt4 book ai didi

c# - 以小端方式将整数转换为字节数组(通用函数)

转载 作者:太空狗 更新时间:2023-10-30 01:33:39 25 4
gpt4 key购买 nike

我有这种方法可以将长字节数组转换为小端字节数组

public static byte[] UnsignedIntegerToLEByteArray(ulong value)
{
// Value in bytes... in your system's endianness (let's say: little endian)
byte[] bytes = BitConverter.GetBytes(value);

// If it was big endian, reverse it
if (!BitConverter.IsLittleEndian)
Array.Reverse(bytes);

return bytes;
}

我的目标是也将它用于短数据类型,如 int、short 等。请参见此处:

byte a = 0xAA;
ushort b = 0xEEAA;
uint c = 0xAABBCCDD;
ulong d = 0xAABBCCDDAAAAAABB;
// If you passed short below, you are only interested
// in first two bytes of the array
byte []tmp = DppUtilities.UnsignedIntegerToLEByteArray(b);

如果我的机器是小端字节序,这会起作用。如果它在大端机器上运行它也会工作吗?我想是的,但我想验证一下。

最佳答案

你可以在 IntPtrMarshal 的帮助下玩一个trick 来转换任何struct (包括byte, ushortulong):

// Disclaimer: the structure will be reversed as a whole, not field by field
public static byte[] ToLEByteArray<T>(T value) where T: struct {
int size = Marshal.SizeOf(typeof(T));
byte[] bytes = new byte[size];

IntPtr p = Marshal.AllocHGlobal(size);

try {
Marshal.StructureToPtr(value, p, true);
Marshal.Copy(p, bytes, 0, size);
}
finally {
Marshal.FreeHGlobal(p);
}

// If it was big endian, reverse it
if (!BitConverter.IsLittleEndian)
Array.Reverse(bytes);

return bytes;
}

....

  Byte b = 123;
ushort s = 123;
ulong l = 123;

Byte[] result_byte = ToLEByteArray(b);
Byte[] result_ushort = ToLEByteArray(s);
Byte[] result_ulong = ToLEByteArray(l);

....

  int i = 123456; 
Byte[] result_int = ToLEByteArray(i);

编辑:问题中的实现有什么问题? (来自评论)。 或者,重申一下这个问题,IntPtrMarshal 的作用是什么?

问题实现的主要问题是初始转换ulong:

  // all the arguments will be converted to ulong 
public static byte[] UnsignedIntegerToLEByteArray(ulong value)

为了说明问题,想象一下,我们有两个值

Byte  x = 0x12;               // 18
ulong u = 0x0000000000000012; // 18

预期的输出是

new byte[] {0x12};                      // for a single byte
new byte[] {0x12, 0, 0, 0, 0, 0, 0, 0}; // for 8 bytes, i.e. ulong

然而,实际输出将是

new byte[] {0x12, 0, 0, 0, 0, 0, 0, 0};

对于 byteulong。如果您想要将数值(byteshortulong 等)写到一个二进制文件,将它们传递给二进制流等:

  using (Stream stm = ...) {
...
Byte[] buffer = UnsignedIntegerToLEByteArray(...);

stm.Write(buffer, offset, buffer.Length); // <- the (possibly!) erroneous write
...
}

关于c# - 以小端方式将整数转换为字节数组(通用函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33097763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com