C ++如何执行按位“或"运算.对负数进行运算? [英] How does C++ do bitwise "or" operations on negative numbers?

查看:72
本文介绍了C ++如何执行按位“或"运算.对负数进行运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我给变量一个这样的值: e = 17 | -15; 时,编译后我得到-15作为答案.我不明白c ++使用什么算术.它如何对负小数位执行按位或"运算?

When I give to a variable such value: e = 17|-15; , I get -15 as an answer after compiling.I can't understand what arithmetic c++ uses. How does it perform a bit-wise OR operation on negative decimals?

推荐答案

它只是对数字的二进制表示进行操作.就您而言,这似乎是二进制补语.

It's just doing the operation on the binary representations of your numbers. In your case, that appears to be two's complement.

 17 -> 00010001
-15 -> 11110001

如您所见,这两个数字的按位 OR 仍为 -15 .

As you can see, the bitwise OR of those two numbers is still -15.

在上面的评论中,您表示您尝试使用两者的补码表示法进行尝试,但是您一定做错了什么.这是逐步的:

In your comments above, you indicated that you tried this with the two's complement representations, but you must have done something wrong. Here's the step by step:

 15 ->  00001111      // 15 decimal is 00001111 binary
-15 -> ~00001111 + 1  // negation in two's complement is equvalent to ~x + 1
-15 ->  11110000 + 1  // do the complement
-15 ->  11110001      // add the 1

这篇关于C ++如何执行按位“或"运算.对负数进行运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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