关于位运算的错误问题
生活随笔
收集整理的這篇文章主要介紹了
关于位运算的错误问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
位運算有這樣一個例題:
編寫一個函數,輸出16位數據的第4位和第10位。
初期我嘗試了使用以下的代碼,但是發現并不能夠正常運行:
#include <stdio.h> #include <stdlib.h>int main() {unsigned int num1,num2;printf("please input a number:\n");scanf("%d",&num1);num2=num1;num1<<=3;num1>>=15;printf("the forth is %d\n",num1);num2<<=9;printf("%d\n",num2);num2>>=15;printf("the tenth is %d\n",num2); } ----------------運行結果如下 please input a number: 1754 //轉換為二進制為0000 0110 1101 1010 the forth is 0 898048 //轉換為二進制為1101 1011 0100 0000 (二進制) the tenth is 27 //此處向右移動15個應該是0000 0000 0000 0001,但是卻傳出了1011 Program ended with exit code: 0在不停的調試過程中發現一直無法解決該問題,甚至按照書上一模一樣的代碼依然存在問題,調試巧合間發現可能是長短整形問題,于是換為以下代碼(長換短):
#include <stdio.h> #include <stdlib.h>int main() {unsigned short int num1,num2;printf("please input a number:\n");scanf("%hu",&num1);num2=num1;num1<<=3;num1>>=15;printf("the forth is %hu\n",num1);num2<<=9;printf("%hu\n",num2);num2>>=15;printf("the tenth is %hu\n",num2); } --------------運行結果如下: please input a number: 1754 the forth is 0 46080 the tenth is 1 Program ended with exit code: 0此時便可以成功,于是深入研究發現,這個算法必須用短整型才是16位數,才能使用左移右移的方式刪去不需要數字達到程序目的,用標準整型會出現保留情況。
總結
以上是生活随笔為你收集整理的关于位运算的错误问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于学生信息录入(文件操作)的心得体会
- 下一篇: 什么是原码、反码和补码?