One of the most popular and perhaps most spread way to represent negative integers in computing is called Two's complement.
Two's complement is a mathematical operation on binary numbers, as well as a binary signed number representation based on this operation
By its definition, to convert a given integer into a negative integer we have to flip the bits by applying the NOT operation and add 1. Two's complement can handle a range expressed by the following formula:
−(2^N−1) to +(2^N−1 − 1)
Our 3 bit example system would therefore cover values from -4 to +3. Its binary representation is shown in the following table:
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
I'm convinced things start to get sense to you now. In the binary table above we can clearly see that negative 1 integer will be represented as 111. As we also know the ~ symbol which is a bitwise NOT operation that inverts the bits the question now is:
So by the following code:
Such idioms are sometimes hard to read but once fully understood it becomes usually a shorter way to write a code. Some programmers don't like these constructs as they are harder to read. I'm not going to agree or defend these opinions as in the end they are question of preferences. The thing is that It's important to be able to read them because you never know where you might need them.
Blog about my programming experiments, tests and so on.