本文介紹了按位運算符簡單地翻轉整數中的所有位?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我必須翻轉整數二進制表示中的所有位.給定:
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.
這篇關于按位運算符簡單地翻轉整數中的所有位?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!