Thursday, March 08, 2007

Bit hack puzzle

A few times I've found myself writing code to threshold greyscale images. In cases where I've really needed performance, I've used MMX and SSE, but yesterday, in the process of running some tests, I wrote a quick implementation in C++ that boiled down to this...

for all pixels in image
   pixel = pixel < 128 ? 0 : 255

It dawned on me that there's a bit hack for this, but I've never seen anyone mention it. If you want the answer, select the next line with your mouse:

pixel = (unsigned char) -((char)(pixel>>7))


Blogger Kilroy Trout said...

Yes indeed and I hate you for thinking of it first :-)

11:37 PM  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home