I recently was using the BinarySearch method and I was curious about why the designers had coded the method with the following for a return value:

"Return Value

The zero-based index of item in the sorted List, if item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count."

(from http://msdn.microsoft.com/en-us/library/w4e7fxsh(v=vs.80).aspx)

I'm not concerned with the magnitude of the return value in my application, just whether it's positive or negative, but why did they not just design it to return the negative of the index of the next element or the negative of Count?

Thanks.

ddanbe commented: Good observation! +8

Because bitwise complement is faster than negating the number (which is done by taking the bitwise complement and adding 1).

For example, let us say that the next element that is larger is 1 (or 0000 0001 binary). The bitwise complement is -2 (1111 1110) and the negation of the number is -1 (1111 1111). They just wanted to save a little time in both converting to and from the result.

commented: Clear, concise answer +6

To find an extra use for the bitwise complement operator?

Because bitwise complement is faster than negating the number (which is done by taking the bitwise complement and adding 1).

For example, let us say that the next element that is larger is 1 (or 0000 0001 binary). The bitwise complement is -2 (1111 1110) and the negation of the number is -1 (1111 1111). They just wanted to save a little time in both converting to and from the result.

Okay. Thanks for clarifying that.

I'll have to refresh my memory on how these steps are translated into CPU cycles.

To find an extra use for the bitwise complement operator?

Is there a committee for the promotion of rarely used operators? lol.

Is there a committee for the promotion of rarely used operators? lol.

In a HUGE organisation ANYTHING is possible, so your statement might be true. I don't say that it is...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.