位操作(C和指標)

來源:互聯網
上載者:User

標籤:style   os   io   for   問題   amp   sp   c   ios   

/*
**編寫一個函數unsigned int reverse_bits(unsigned int value);這個函數的返回值是把value的二進位位元模式從左至右變換一下後的值。
**例如在32位機器上,25這個值包含下列各位00000000000000000000000000011001   函數的返回值應該是10011000 0000 0000 0000 0000 0000 0000
*編寫函數時要注意不要讓它依賴於你的機器上整形值得長度00000000000000000000000000000001

*/


#include <iostream>
using namespace std;
unsigned int reverse_bits(unsigned int value)
{
unsigned int answer;
unsigned int i;


answer =0;
/*
**只要i不是0就繼續運行,這就使迴圈與機器的字長無關,從而避免了可移植性問題
*/


for (i =1;i != 0;i<<=1)
{
//把舊的answer左移一位,為下一個位留下空間。如果value的最後一位是1,answer就與1進行or操作,然後將value右移至下一個位
answer <<=1;
if (value & 1)
{
answer |= 1;
}
value >>=1;
}
return answer;
}
int main()
{
unsigned int ans;
unsigned int ans2;
//ans=reverse_bits(24);
ans2=reverse_bits(25);
cout<<ans<<endl;
cout<<ans2<<endl;
}

雖然看起來有點簡單但是邏輯性相當強,自己對於位操作處理的非常少!

位操作(C和指標)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.