c# – 以小端方式整数到字节数组(泛型函数)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 以小端方式整数到字节数组(泛型函数),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2307字,纯文字阅读大概需要4分钟。
内容图文
![c# – 以小端方式整数到字节数组(泛型函数)](/upload/InfoBanner/zyjiaocheng/788/7fb1825274944d18a8f8f9f96d4bf402.jpg)
我有这个方法来转换长到小端字节数组
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);
如果我的机器是小端,这可以工作.
如果在big endian机器上运行它也会工作吗?我想是的,但我想验证一下.
解决方法:
你可以在IntPtr和Marshal的帮助下玩一个技巧来转换任何结构(包括byte,ushort和ulong):
// 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);
编辑:问题的实施有什么问题? (来自评论).
或者,重申一下这个问题,那么IntPtr,Marshal的内容是什么?
问题实现的主要问题是初始转换为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};
对于byte和ulong.如果您想要将数值(byte,short,ulong等)写入二进制文件,将它们传递给二进制流等,这种不当行为可能会导致问题:
using (Stream stm = ...) {
...
Byte[] buffer = UnsignedIntegerToLEByteArray(...);
stm.Write(buffer, offset, buffer.Length); // <- the (possibly!) erroneous write
...
}
内容总结
以上是互联网集市为您收集整理的c# – 以小端方式整数到字节数组(泛型函数)全部内容,希望文章能够帮你解决c# – 以小端方式整数到字节数组(泛型函数)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。