Write function on c# which converts int to ushort array with check of little or big endian
- User
Write function on c# which converts int to ushort array with check of little or big endian
- Assistant
In C#, you can create a function that converts an
intinto an array ofushortvalues, taking into account the system's endianness (little or big endian). Below is the example of such a function:using System; public class IntToUShortArrayConverter { public static ushort[] ConvertIntToUShortArray(int value) { // Allocate a ushort array with 2 elements since an int is 4 bytes and a ushort is 2 bytes ushort[] result = new ushort[2]; if (BitConverter.IsLittleEndian) { // If system is little endian, lower order bytes should come first result[0] = (ushort)(value & 0xFFFF); // Get the lower 16 bits result[1] = (ushort)((value >> 16) & 0xFFFF); // Get the upper 16 bits } else { // If system is big endian, higher order bytes should come first result[1] = (ushort)(value & 0xFFFF); // Get the lower 16 bits result[0] = (ushort)((value >> 16) & 0xFFFF); // Get the upper 16 bits } return result; } // Main Method for testing the function static void Main(string[] args) { // Example usage int exampleInt = 0x12345678; ushort[] ushortArray = ConvertIntToUShortArray(exampleInt); Console.WriteLine(BitConverter.IsLittleEndian ? "Little endian system detected." : "Big endian system detected."); foreach (var ushortValue in ushortArray) { Console.WriteLine("0x" + ushortValue.ToString("X4")); // Display each ushort in hexadecimal } } }