Integer Minimum or Maximum

| No Comments

Given 2's complement integer values x and y, the minimum can be computed without any branches as x+(((y-x)>>(WORDBITS-1))&(y-x)). Logically, this works because the shift by (WORDBITS-1) replicates the sign bit to create a mask -- be aware, however, that the C language does not require that shifts are signed even if their operands are signed, so there is a potential portability problem. Additionally, one might think that a shift by any number greater than or equal to WORDBITS would have the same effect, but many instruction sets have shifts that behave strangely when such shift distances are specified.

Of course, maximum can be computed using the same trick: x-(((x-y)>>(WORDBITS-1))&(x-y)).

[Listening to: Queen Bitch (live) - David Bowie - RarestOneBowie (3:15)]

Leave a comment

About this Entry

This page contains a single entry by Pete Shanahan published on November 30, 2005 1:23 PM.

Dual-Linked List with One Pointer Field was the previous entry in this blog.

Integer Selection is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.