如何为int转换为Little Endian字节数组? [英] How to convert an int to a little endian byte array?

查看:99
本文介绍了如何为int转换为Little Endian字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个功能在C#中小端字节数组转换为一个整数:

I have this function in C# to convert a little endian byte array to an integer number:

int LE2INT(byte[] data)
{
  return (data[3] << 24) | (data[2] << 16) | (data[1] << 8) | data[0];
}

现在我想将其转换回小尾数..
类似

Now I want to convert it back to little endian.. Something like

byte[] INT2LE(int data)
{
  // ...
}

任何想法?

感谢。

推荐答案

刚刚扭转,<击>注意,这本code(像其他)只能小端机器上。(编辑 - 这是错误的,因为这code。通过定义返回LE)

Just reverse it, Note that this this code (like the other) works only on a little Endian machine. (edit - that was wrong, since this code returns LE by definition)

  byte[] INT2LE(int data)
  {
     byte[] b = new byte[4];
     b[0] = (byte)data;
     b[1] = (byte)(((uint)data >> 8) & 0xFF);
     b[2] = (byte)(((uint)data >> 16) & 0xFF);
     b[3] = (byte)(((uint)data >> 24) & 0xFF);
     return b;
  }

这篇关于如何为int转换为Little Endian字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆