Pages: [1]   Go Down
Author Topic: shiftOut code and double not (!!)?  (Read 976 times)
0 Members and 1 Guest are viewing this topic.
Toronto
Offline Offline
Jr. Member
**
Karma: 0
Posts: 70
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

This question is for mellis more than anyone, but I figured I might as well post it publicly in case someone else might find it useful.

I've been going through the code that defines all the built-in functions to make sure I understand what's going on, and I noticed this in shiftOut:

Code:
digitalWrite(dataPin, !!(val & (1 << i)));

I'm wondering what the double exclamation is for; doesn't applying the NOT operator twice just leave the input unchanged? When I wrote my own version of a shiftOut function without them, it seemed to work fine; in the ShiftOut tutorial they don't have them.

Any insight? Thanks!

Logged

Forum Administrator
Cambridge, MA
Offline Offline
Faraday Member
*****
Karma: 11
Posts: 3538
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

It's not very good style, and probably not necessary, but it converts anything besides 0 to 1, just in case digitalWrite() only accepted 1 for HIGH.  That is, !!5 is 1, and !!0 is 0.
Logged

Toronto
Offline Offline
Jr. Member
**
Karma: 0
Posts: 70
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

I see, and I see how that could be a useful trick. However, doesn't the & operator already guarantee that the result will be only 0 or 1? (I guess you did say it was probably not necessary, I'm just trying to figure out if there's any possibility it would be necessary.)
Logged

Forum Administrator
Cambridge, MA
Offline Offline
Faraday Member
*****
Karma: 11
Posts: 3538
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Nope, because, for example, 5 & (1 << 2) is 4, not 1.  Really, I should have used (val >> i) & 1 instead.
Logged

Toronto
Offline Offline
Jr. Member
**
Karma: 0
Posts: 70
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
Nope, because, for example, 5 & (1 << 2) is 4, not 1.  Really, I should have used (val >> i) & 1 instead.

I see. That's great! Thanks for the explanation!
Logged

Sacramento, CA, USA
Offline Offline
Newbie
*
Karma: 0
Posts: 30
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

or (val >> i) != 0
Logged

Pages: [1]   Go Up
Jump to: