how to use inverse in C

荒凉一梦 提交于 2019-12-04 22:33:34

Use XOR operator:

Alpha.b = Alpha.a ^ 1;

In C, true is represented by 1, and false by 0. However, in a comparison, any non-false value is treated is true.

The ! operator does boolean inversion, so !0 is 1 and !1 is 0.

The ~ operator, however, does bitwise inversion, where every bit in the value is replaced with its inverse. So ~0 is 0xffffffff (-1). ~1 is 0xfffffffe (-2). (And both -1 and -2 are considered as true, which is probably what's confusing you.)

What you want is !, instead of ~.

The ~ operator negates each individual bit. For example, assume that Alpha.a is an unsigned char. Then ~1 would read, in binary as, ~00000001, and the result would be 11111110 (again, in binary), which is the same as 254 in decimal and 0xFE in hex.

As others have suggested, use !Alpha.a or Alpha.a ^ 1.

A nice cross-platform cross language solution to this common problem is:

Alpha.b = 1 - Alpha.a;

You can't use ~ as this will turn 00000000 into 11111111 rather than 00000001 as I think you're expecting.

If you have bools you can use:

Alpha.b = !(Alpha.a)

but if not you may have to use if / else logic:

if (Alpha.a == 0)
{
    Alpha.b = 1;
}
else
{
    Alpha.b = 0;
}

What about a postoperational bitmask?

using unsigned chars looking for bit0:

b = 0x01u & ( ~a );

or even

b = a ^ 0x01u;

or for "Boolean-Thinkers" ( be aware TRUE and FALSE may differ from 0/1 ! if you want it "real boolean" you should use TRUE and FALSE if defined.)

b = (1 != a)?(0u):(1u);

Cheers

You want to use another operator. Specifically !

Alpha.b = !Alpha.a

Since the values are zero or one, it is much simplier.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!