To expand my comment: you'll need to use IoC (Inversion of Control) to inject a BitConverterEx
instance where you need it. This class has a single "parameter": the endianness of the output byte[]
that it will read/write.
In the end this problem is similar to the common problem "how can I mock DateTime.Now
"
In the unit tests, instead of injecting a BitConverterEx
you can inject the ManipulableBitConverterEx
where you can control the processor flag. Or more correctly you should unit test independently the BitConverterEx
and your classes, so that when you test 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 many times this class, Array.Reverse
could be "slow". There are solutions to invert the endianness of data types that manipulate the single bytes using shift, or, xor, ...
BitConverter.IsLittleEndian
that can be "manipulated" externally by unit tests. This class implements all the needed methods ofBitConverter
, and ifrequiredEndianness == savedIsLittleEndian
then it directy usesBitConverter
, else it usesBitConverter + Array.Reverse
. You write the unit tests for this class and live happy. – Trot