简体   繁体   中英

Convert array of Ints into array of Little-Endian Bytes in C#

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM