public static int CompareTo(this byte[] leftSide, byte[] rightSide, bool signed) { // A method to compare two byte arrays arithmetically. There are 3 possible return values. // 0: The arrays were equal. // 1: The left side was greater than the right. // 3: The right side was greater than the left. // PadEqual sign/zero extends(depending on $signed) the smallest operand to the greatest length of the two input arrays // If they are both equal in length, nothing happens. Bitwise.PadEqual(ref leftSide, ref rightSide, signed); // The main algorithm will not work on inputs with different signs because it doesn't consider the weight of the MSB in twos compliment. if (signed) { // Get the signs of the inputs bool LeftSign = leftSide.IsNegative(); bool RightSign = rightSide.IsNegative(); // The following statement will evaluate as true if exactly one of the signs are on. In this case it is immediately clear which is greater. if ((LeftSign ^ RightSign) == true) { // If the left side is negative, return -1, because the right side must have been positive for the XOR to work. return(LeftSign ? -1 : 1); } } // As little endian is exclusively worked with, work backwards. This means that the bytes in the array are compared in order of magnitude. // For example, // When comparing two base 10 numbers, 10 and 21, the 0 and 1 digits can be completely ignored, only the tens column is needed to determine the outcome. // The numbers could be, // 1, 2 // 10000, 21000 // The result is the same. This allows the problem to be abstracted. Naturally, the numbers had to be padded to the correct size with their value preserved // which has already been done. // -The most significant column difference dictates which value is greater. This can be used instead of subtraction to determine the result, which is more // performant because no unecessary operations are carried out. for (int i = leftSide.Length - 1; i >= 0; i--) { // If the two indexes are not the same value, the two inputs cannot be equal, the result can be determined here. if (leftSide[i] != rightSide[i]) { // Return 1 if the most significant column difference of leftSide is greater than that of rightSide, -1 if it is not. return(leftSide[i] > rightSide[i] ? 1 : -1); } } // If the method hasn't returned already, the two inputs must be equal return(0); }