按位运营商简单地翻转所有位整数? [英] Bitwise operator for simply flipping all bits in an integer?

查看:167
本文介绍了按位运营商简单地翻转所有位整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要翻转所有位整数的二进制重新presentation。鉴于:

I have to flip all bits in a binary representation of an integer. Given:

10101

输出应

01010

什么是位运算符与一个整数使用时,做到这一点?例如,如果我在写像 INT flipBits(INT N)的方法; ,你会在身上去了?我需要翻转只有什么是已经present的数量,而不是在所有的整数32位。

What is the bitwise operator to accomplish this when used with an integer? For example, if I were writing a method like int flipBits(int n);, what would go in the body? I need to flip only what's already present in the number, not all 32 bits in the integer.

推荐答案

单目运算符是按位否定。如果你需要比在什么适合较少的比特 INT 那么你就需要使用&放大器来掩盖它;之后事实。

The ~ unary operator is bitwise negation. If you need fewer bits than what fits in an int then you'll need to mask it with & after the fact.

这篇关于按位运营商简单地翻转所有位整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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