Subj : Re: possible overflow? To : comp.programming From : Rob Somers Date : Sat Aug 27 2005 09:00 am > !0 = 1 > !1 = 0 > !2 = 0 > etc. > > Another negation swaps the 0 and 1 again, so basically 0 remains 0, > and any other value becomes 1. > > 'mask' has a single bit set, each loop it's shifted one position. > > If you AND 'input' with 'mask', the result is zero when the Nth bit > of 'input' is clear, and it's non-zero when it's set. > > So, !!(input & mask) equals 0 if the 'current' bit is clear, > and 1 if it is set. > > '0' is the ASCII value of the character 0. > If you add one to that, you get the ASCII value of the character 1. > > So, the end result is '0' if the bit is clear, and '1' if it is set. > > > A direct and clear way to write this would be: > > putchar((input & mask) ? '1' : '0'); > > > But that might(*) be less efficient, so the double-negation trick > is favoured by some programmers. > However, the following might even be more efficient: > > putchar('1' - !(input & mask)); > > Try to work out for yourself how that one works. > > > *) With any luck, a decent optimizing compiler will produce > equally fast code for the clear way, and it might even be faster. > For the record: gcc produces *the same* code for all three lines. > > > SaSW, Willem I feel enlightened now. :) Thanks for being so thorough in your explanation. Rob Somers .