I have two character arrays (each of many bytes in length; for example each can be 10-12 bytes) and they represent a number in binary format. I want to check if one number is larger than the other. What is the most efficient way to check which of the two is the largest? Are there bitwise operations that one can perform to efficiently determine this?
Share
I think what you can do is firstly use two pointers to point at the first nonzero byte in both (from the left). If now the two effective lengths are different, output the longer one. I mean, let’s assume that
firstis 10 bytes andsecondis 12 bytes. Byte 4 (first[3]) is the first nonzero byte infirst, and byte 2 (second[1]) is the first nonzero byte insecond. Now the effective length offirstis 7 bytes, while that ofsecondis 11. Clearly,secondis larger.Now for equal effective lengths. Compare the bytes. If equal, go to the next. Otherwise, the larger byte exists in the larger number and we finish.
You can speed this operation up by comparing register-sized chunks (I mean chunks that fill the whole register), because if both chunks are equal you’ll skip a number of comparisons equal to the size of the register in bytes… if they are unequal, you can compare byte-by-byte, or you can even compare half-size by half-size firstly… if equal, skip to the other half. If different, then compare quarter-size by quarter-size, and so on before comparing byte-by-byte (this is analogous to binary search).