To expand my comment: you need to use IoC (Inversion of Control) to inject the BitConverterEx instance where you need it. This class has a single โparameterโ: the end result of the byte[] output that it will read / write.
In the end, this problem is similar to the general โhow can I make fun of DateTime.Now โ problem
In unit tests, instead of entering BitConverterEx you can enter ManipulableBitConverterEx , where you can control the processor flag. Or rather, you must unit test independently BitConverterEx and your classes so that when testing your classes you know that the results of BitConverterEx are correct.
public class BitConverterEx { public bool ProcessorLittleEndian { get; protected set; } public bool DataLittleEndian { get; protected set; } public BitConverterEx(bool dataLittleEndian) { ProcessorLittleEndian = BitConverter.IsLittleEndian; DataLittleEndian = dataLittleEndian; } public byte[] GetBytes(int value) { byte[] bytes = BitConverter.GetBytes(value); if (DataLittleEndian != ProcessorLittleEndian) { Array.Reverse(bytes); } return bytes; } public int ToInt32(byte[] value, int startIndex) { if (DataLittleEndian == ProcessorLittleEndian) { return BitConverter.ToInt32(value, startIndex); } byte[] value2 = new byte[sizeof(int)]; Array.Copy(value, startIndex, value2, 0, value2.Length); Array.Reverse(value2); return BitConverter.ToInt32(value2, 0); } } public class ManipulableBitConverterEx : BitConverterEx { public ManipulableBitConverterEx(bool processorLittleEndian, bool dataLittleEndian) : base(dataLittleEndian) { ProcessorLittleEndian = processorLittleEndian; } }
Note that if you need to reuse this class, Array.Reverse can be "slow." There are solutions to invert the contentability of data types that control single bytes with shift, or, xor, ...
source share