I need to convert a large array of ints into an array of their little endian byte representations. Is there a function that converts the array or is the only way to loop through and "manually" convert each one.
Asked
Active
Viewed 313 times
1
-
[`.Select`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=net-6.0) – Nick is tired Feb 18 '22 at 16:25
-
2Do you expect he output to be `byte[]` or `byte[][]`? – Magnetron Feb 18 '22 at 16:25
-
Please show an example of what your input is and what your expected output is. And also show what you have already tried – derpirscher Feb 18 '22 at 16:26
-
2Does this answer your question? [How to convert an int to a little endian byte array?](https://stackoverflow.com/questions/2350099/how-to-convert-an-int-to-a-little-endian-byte-array) – Peter Smith Feb 18 '22 at 16:26
-
Whether you use a loop or `linq` at some level you have to loop through your array – Peter Smith Feb 18 '22 at 16:27
-
Are you running this on a little-endian machine, or must the solution be endian-agnostic? – Matthew Watson Feb 18 '22 at 16:32
-
Note that `BinaryPrimitives` was added since that linked answer was written – canton7 Feb 18 '22 at 16:34
1 Answers
2
One thing you could do is use the EndianBitConverter project from Nuget. It does what it says on the tin and provides a way of converting to either big-endian or little-endian.
Once you have got it installed, you can write code like this:
var intList = new List<int> { 91233, 67278, 22345, 45454, 23449 };
foreach ( var n in intList)
{
var result1 = EndianBitConverter.LittleEndian.GetBytes(n);
var result2 = EndianBitConverter.BigEndian.GetBytes(n);
}
If you want to do it as a 1 liner, then perhaps something like this:
var intList = new List<int> { 91233, 67278, 22345, 45454, 23449 };
var result = intList.Select(x => EndianBitConverter.LittleEndian.GetBytes(x)).ToList();

Ocean Airdrop
- 2,793
- 1
- 26
- 31