C语言中如何使用逆函数
[如何使用 ~ 运算符]
我有一个结构说 Alpha
。我知道 Alpha
内元素的值(例如 a
),可以是 0
或 1
- 我想要相同结构的其他元素取 Alpha.a 的倒数。例如:
if Alpha.a = 1
then Alpha.b = 0
反之亦然,
我尝试过:
Alpha.b = ~ (Alpha.a)
但不幸的是它不起作用 - 当 Alpha.a
为 1
时,Alpha.b
设置为254
有什么想法吗?
谢谢和问候,
萨姆普拉特
[how to use ~ operator ]
I have a structure say Alpha
. I know the value of element inside Alpha
(say a
) which can be 0
or 1
- I want the other element of same structure to take inverse value of Alpha.a. For example:
if Alpha.a = 1
then Alpha.b = 0
and vice versa
I have tried:
Alpha.b = ~ (Alpha.a)
But unfortunately it doesnt work - when Alpha.a
is 1
, Alpha.b
gets set to 254
Any ideas?
Thanks and regards,
SamPrat
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在 C 语言中,
true
用 1 表示,false
用 0 表示。但是,在比较中,任何非 false 值都被视为 true。!
运算符执行布尔值反转,因此 !0 为 1,!1 为 0。然而,
~
运算符执行按位运算 反转,其中值中的每一位都被其反转替换。所以 ~0 是 0xffffffff (-1)。 ~1 是 0xfffffffe (-2)。 (-1 和 -2 都被认为是 true,这可能会让您感到困惑。)您想要的是
!
,而不是~
。In C,
true
is represented by 1, andfalse
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~
.使用异或运算符:
Use XOR operator:
~
运算符对每个单独的位取反。例如,假设Alpha.a
是一个unsigned char
。然后~1
将以二进制形式读取为~00000001,结果将是11111110(同样是二进制),这与十进制的254和十六进制的0xFE相同。正如其他人所建议的,使用
!Alpha.a
或Alpha.a ^ 1
。The
~
operator negates each individual bit. For example, assume thatAlpha.a
is anunsigned 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
orAlpha.a ^ 1
.针对这个常见问题的一个很好的跨平台跨语言解决方案是:
A nice cross-platform cross language solution to this common problem is:
操作后位掩码怎么样?
使用无符号字符寻找 bit0:
或什至
真正的布尔值”,你应该使用 TRUE 和 FALSE(如果已定义)。)
或“Boolean-Thinkers”(请注意 TRUE 和 FALSE 可能与 0/1 不同!如果你想要它“
What about a postoperational bitmask?
using unsigned chars looking for bit0:
or even
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.)
Cheers
您不能使用
~
因为这会将00000000
变成11111111
而不是00000001
因为我认为您是期待。如果你有布尔值,你可以使用:
但如果没有,你可能必须使用 if / else 逻辑:
You can't use
~
as this will turn00000000
into11111111
rather than00000001
as I think you're expecting.If you have bools you can use:
but if not you may have to use if / else logic:
您想使用另一个运算符。具体来说 !
由于值为零或一,因此要简单得多。
You want to use another operator. Specifically !
Since the values are zero or one, it is much simplier.