Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# - How to convert an int to a little endian byte array?

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)
{
  // ...
}

Any idea?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The BitConverter class can be used for this, and of course, it can also be used on both little and big endian systems.

Of course, you'll have to keep track of the endianness of your data. For communications for instance, this would be defined in your protocol.

You can then use the BitConverter class to convert a data type into a byte array and vice versa, and then use the IsLittleEndian flag to see if you need to convert it on your system or not.

The IsLittleEndian flag will tell you the endianness of the system, so you can use it as follows:

This is from the MSDN page on the BitConverter class.

  int value = 12345678; //your value
  //Your value in bytes... in your system's endianness (let's say: little endian)
  byte[] bytes = BitConverter.GetBytes(value);
  //Then, if we need big endian for our protocol for instance,
  //Just check if you need to convert it or not:
  if (BitConverter.IsLittleEndian)
     Array.Reverse(bytes); //reverse it so we get big endian.

You can find the full article here.

Hope this helps anyone coming here :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...