C或C++沒有直接讀取內存中二進制碼的操作,只有自己編寫代碼實現
*************************************************************************************/
#include<iostream>
using namespace std;
int a[50]; //存儲這些整數
int bits[32]; //存儲每壹個整數的32位二進制
void getBits(int n); //函數原型聲明
void main()
{
int n=0;
int i;
int j;
char endChar; //輸入結束標識符
cout<<"Input the integers:"<<endl;
do
{
cin>>a[n++];
endChar=cin.peek(); //獲取下壹個字符
}while(endChar != '\n'); //如果沒有按下回車則繼續輸入
for(i = 0; i < n; i++) //輸出每壹個整數二進制碼
{
getBits(a[i]); //將每壹個正整數的32位二進制碼寫入數組bits
if(a[i] < 0) //如果n小於零需則求反碼
{
for(j = 31; j >= 0; j--)
{
bits[j] = ~bits[j] + 2; //按數值取反
}
bits[0] += 1; //最低位加1
for(j = 0; j < 32; j++) //處理進位
{
if(bits[j] == 2)
{
if(j == 32)
{
cout<<"溢出錯誤"<<endl;
exit(0);
}
bits[j] = 0;
bits[j+1] += 1;
}
}
}
for(j = 31; j >= 0; j--)
{
cout<<bits[j];
}
cout<<" "<<a[i]<<endl;
}
}
/***************************************************************************************
函數名稱 getBits
函數功能 將每壹個正整數的32位二進制碼寫入數組bits
參數類型 int
返回類型 void
編碼人員 passion_wu128
****************************************************************************************/
void getBits(int n)
{
int i;
if(n < 0)
{
//確保是對正整數操作
n = -n;
}
for(i = 0; i < 32; i++) //依次得到每壹個二進制位
{
bits[i] = n%2;
n /= 2;
}
}
測試樣例:
Input the integers:
5 12 -12 48 -168
00000000000000000000000000000101 5
00000000000000000000000000001100 12
11111111111111111111111111110100 -12
00000000000000000000000000110000 48
11111111111111111111111101011000 -168
請按任意鍵繼續. . .
是否可以解決您的問題?