Not (~) and bitRead()

I would like to read a bit from a number, and then take the opposite of that bit.

Right now I have something like this that reads the bit (part of loop that goes through and reads each bit of num1).

byte state1 = bitRead(num1,i);

If I do:

byte state1 = ~bitRead(num1,i);

Will that work? Or will it give me ~(00000001) = 11111110 instead?

Or could I use the boolean not instead of the bitwise not?

byte state1 = !bitRead(num1,i);

I know I could just do an if statement...but it seems like there should be a better/more straightforward way to do this.

it is returning a zero or a one...

how would you invert a byte...

try it!

byte myByte = B00000001;
void setup()
{
  Serial.begin(9600);
  byte myData = !bitRead(myByte, 0);// replace ! with a ~ and see...
  Serial.println(myData, BIN); 
}

void loop()
{
 
}

When I was doing my masters in software engineering, we were taught not to make assumptions about the definition of true and false by not casting true and false to other types. The biggest reason for this was side effects.

What if someone decides to define true and false like so?

#define FALSE (0)
#define TRUE (!(FALSE))

Now if you do

char x = TRUE;    //x is now 0x11111111
if(x == 1)
{
   //won't happen.
}

If you want to use booleans, use booleans:

bool val = bitRead(myByte, 0);
char myData = val?0x11111111:0x00000001;

bitRead will always return a 0 or 1 as you can see:

#define bitRead(value, bit) (((value) >> (bit)) & 0x01)

So the inverse would be !bitRead. Thus doing the logical negation would also return 0 or 1.

According to the C++ standard:

The operand of the logical negation operator ! is contextually converted to bool (Clause 4); its value is
true if the converted operand is false and false otherwise. The type of the result is bool.

...

A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true
becoming one.

Thus the C++ true and false are (can be treated as) indeed 1 and 0 and not something else.


Using ~ is not logical negation. That is a ones-complement.

RobvdVeer:
What if someone decides to define true and false like so?

#define FALSE (0)

#define TRUE (!(FALSE))

Yes, but TRUE and FALSE are not true and false.

If I decide to declare:

#define FOO (0)
#define BAR (!(FOO))

And then do this:

char x = BAR;    //x is now 0x11111111
if(x == 1)
{
   //won't happen.
}

Well, that's my problem. But logically there is no reason to assume BAR is 1 or any other thing. That's an argument for not using "magic numbers" in your code, in this case 1.

What would be valid is this:

char x = TRUE;    //x is now 0x11111111
if(x)
{
   //will happen.
}

After all, non-zero is treated as true in an "if".