Bitwise operator for simply flipping all bits in an integer?(按位运算符简单地翻转整数中的所有位?)
问题描述
我必须翻转整数二进制表示中的所有位.给定:
I have to flip all bits in a binary representation of an integer. Given:
10101
输出应该是
01010
当与整数一起使用时,完成此操作的位运算符是什么?例如,如果我正在编写像 int flipBits(int n); 这样的方法,那么主体中会发生什么?我只需要翻转数字中已经存在的内容,而不是整数中的所有 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.
这篇关于按位运算符简单地翻转整数中的所有位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:按位运算符简单地翻转整数中的所有位?
基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
