問題描述
我必須翻轉(zhuǎn)整數(shù)二進制表示中的所有位.給定:
I have to flip all bits in a binary representation of an integer. Given:
10101
輸出應(yīng)該是
01010
當與整數(shù)一起使用時,完成此操作的位運算符是什么?例如,如果我正在編寫像 int flipBits(int n);
這樣的方法,那么主體中會發(fā)生什么?我只需要翻轉(zhuǎn)數(shù)字中已經(jīng)存在的內(nèi)容,而不是整數(shù)中的所有 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.
推薦答案
~
一元運算符是按位取反.如果您需要的位數(shù)少于 int
中的位數(shù),那么您需要在事后使用 &
對其進行屏蔽.
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.
這篇關(guān)于按位運算符簡單地翻轉(zhuǎn)整數(shù)中的所有位?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!