查詢給定數字的 2 的補碼的 C 語言程式


可透過兩種方法來計算給定二進位制數的 2 的補碼,如下所示 −

  • 方法 1 − 將給定的二進位制數轉換為 1 的補碼,然後加 1。

  • 方法 2 − 找到從最低有效位 (LSB) 開始幷包括位保持不變的第一個設定位之後的尾隨零,並對所有其他位取補。

查詢給定二進位制數的 2 的補碼的邏輯如下 −

for(i = SIZE - 1; i >= 0; i--){
   if(one[i] == '1' && carry == 1){
      two[i] = '0';
   }
   else if(one[i] == '0' && carry == 1){
      two[i] = '1';
      carry = 0;
   } else {
      two[i] = one[i];
   }
}
two[SIZE] = '\0';
printf("Two's complement of binary number %s is %s
",num, two);

查詢給定二進位制數的 1 的補碼的邏輯為 −

for(i = 0; i < SIZE; i++){
   if(num[i] == '0'){
      one[i] = '1';
   }
   else if(num[i] == '1'){
      one[i] = '0';
   }
}
one[SIZE] = '\0';
printf("Ones' complement of binary number %s is %s
",num, one);

範例

以下是用來查詢給定數字的 2 的補碼的 C 語言程式 −

 實際演示

#include<stdio.h>
#include<stdlib.h>
#define SIZE 8
int main(){
   int i, carry = 1;
   char num[SIZE + 1], one[SIZE + 1], two[SIZE + 1];
   printf("Enter the binary number
");    gets(num);    for(i = 0; i < SIZE; i++){       if(num[i] == '0'){          one[i] = '1';       }       else if(num[i] == '1'){          one[i] = '0';       }    }    one[SIZE] = '\0';    printf("Ones' complement of binary number %s is %s
",num, one);    for(i = SIZE - 1; i >= 0; i--){       if(one[i] == '1' && carry == 1){          two[i] = '0';       }       else if(one[i] == '0' && carry == 1){          two[i] = '1';          carry = 0;       }       else{          two[i] = one[i];       }    }    two[SIZE] = '\0';    printf("Two's complement of binary number %s is %s
",num, two);    return 0; }

輸出

當執行上述程式時,它將產生以下結果 −

Enter the binary number
1000010
Ones' complement of binary number 1000010 is 0111101
Two's complement of binary number 1000010 is 0111110

更新於: 2021 年 3 月 24 日

14K+ 瀏覽次數

開啟您的事業

完成課程以獲取認證

開始
廣告
© . All rights reserved.