按位补码运算符(〜波浪号)如何工作? [英] How does the bitwise complement operator (~ tilde) work?

查看:144
本文介绍了按位补码运算符(〜波浪号)如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么〜2等于-3? ~运算符如何工作?

Why is it that ~2 is equal to -3? How does ~ operator work?

推荐答案

请记住,负数存储为正数的 2的补码.例如,这是-2的补码表示形式:(8位)

Remember that negative numbers are stored as the two's complement of the positive counterpart. As an example, here's the representation of -2 in two's complement: (8 bits)

1111 1110

您可以用数字的二进制表示形式,取其补码(将所有位取反)并加一个来获得此结果.两个以0000 0010开头,通过将位取反得到11111101.加一个得到上面的结果.第一位是符号位,表示负数.

The way you get this is by taking the binary representation of a number, taking its complement (inverting all the bits) and adding one. Two starts as 0000 0010, and by inverting the bits we get 1111 1101. Adding one gets us the result above. The first bit is the sign bit, implying a negative.

所以让我们看一下如何获得〜2 = -3:

So let's take a look at how we get ~2 = -3:

这里又是两个:

0000 0010

简单地翻转所有位,我们得到:

Simply flip all the bits and we get:

1111 1101

那么,补码中的-3是什么样的?从正数3开始:0000 0011,将所有位翻转到1111 1100,然后加一成为负值(-3)11111101.

Well, what's -3 look like in two's complement? Start with positive 3: 0000 0011, flip all the bits to 1111 1100, and add one to become negative value (-3), 1111 1101.

因此,如果您简单地将2中的位取反,您将获得-3的二进制补码表示形式.

So if you simply invert the bits in 2, you get the two's complement representation of -3.

这篇关于按位补码运算符(〜波浪号)如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆