格雷碼及其逆的十進位制等價
格雷碼或反射二進位制碼是一種二進位制數字表示形式,其中兩個連續的數字僅一位不同。
例如,1 的格雷碼是 001,而 2 的格雷碼是 011。
格雷碼通常用於錯誤校正,因為它可以防止在狀態變化期間可能發生在普通二進位制表示中的某些資料錯誤。
由於其獨特的特性,格雷碼在卡諾圖、通訊等方面也很有用。
先決條件
在繼續閱讀之前,請學習十進位制、二進位制和格雷碼錶示法。
問題陳述 1
給定一個十進位制數 n,求該數的格雷碼的十進位制形式。
示例
Input: 3 Output: 2
解釋 -> 3 的二進位制表示為 011。其格雷碼錶示為 010。010 的十進位制等價為 2。
因此,3 的格雷碼的十進位制等價為 2。
Input: 5 Output: 7
解釋 -> 5 的二進位制表示為 101。其格雷碼錶示為 111,其十進位制等價為 7。
因此,5 的格雷碼的十進位制等價為 7。
解決方案
編譯器以二進位制格式理解數字。
因此,在我們的程式中,當我們以十進位制格式輸入一個數字時,它會被解釋為二進位制。
因此,我們只需要將一個數字從其二進位制等價轉換為其格雷碼。
二進位制到格雷碼轉換
二進位制表示和格雷碼的最左邊的位是相等的。右側的後續位可以透過取連續二進位制位的異或來找到。
例如 -
考慮 n = 3。3 的二進位制程式碼為 011。
二進位制和格雷碼的最左邊的位是相等的。因此,格雷碼中最左邊的一位是 0。
對於從左邊數起的第二位,對二進位制程式碼中從左邊數起的第 1 位和第 2 位進行異或運算。0 XOR 1 = 1。
對於從左邊數起的第三位,對二進位制程式碼中從左邊數起的第 2 位和第 3 位進行異或運算。1 XOR 1 = 0。
因此格雷碼:010。
演算法:使用按位運算子
我們可以透過以下步驟獲得數字 n 的格雷碼 -
將 n 右移 1 位。
將右移後的數字與原始 n 進行異或運算。
示例
下面是一個使用按位運算子從二進位制程式碼查詢格雷碼的 C++ 程式
#include <bits/stdc++.h>
using namespace std;
//This function returns the decimal equivalent
// of the gray code of n.
int dec_equi_of_gray(int n) {
return n ^ (n >> 1);
}
int main(){
int n = 3;
cout<<"The decimal equivalent of the gray code of 3 is: ";
//Function call to convert binary code to gray code
cout << dec_equi_of_gray(n) << endl;
return 0;
}
輸出
The decimal equivalent of the gray code of 3 is: 2
問題陳述 2
給定格雷碼的十進位制值,求其十進位制程式碼值。
示例
Input: 15 Output: 10
解釋 -> 給定作為輸入的格雷碼:1111(15 的二進位制值)。
現在,將格雷碼轉換為二進位制碼得到 1010 從 1111。
而 1010 是 10 的二進位制值。因此,輸出。
Input: 10 Output: 12
解釋 -> 給定作為輸入的格雷碼:1010(10 的二進位制值)。
格雷碼 1010 的二進位制碼為 1100。而 1100 在十進位制中為 12。
格雷碼到二進位制碼轉換
二進位制碼的最左邊的位(MSB)與格雷碼的 MSB 相同。後續位可以透過取前一個索引二進位制位與當前索引格雷位的異或來找到。
例如:考慮格雷碼 1111。
二進位制碼的 MSB 將與格雷碼的 MSB 相同。因此,MSB 將為 1。
對於第二左邊的位,檢查格雷碼的第二左邊的位與二進位制碼的最左邊的位的異或。因此,1 ^ 1 = 0。
類似地,對於第三左邊的位,0 ^ 1 = 1。
對於第四左邊的位,1 ^ 1 = 0。
因此二進位制碼:1010。
示例
下面是一個使用按位運算子從格雷碼查詢二進位制碼的 C++ 程式
#include <bits/stdc++.h>
using namespace std;
//This function returns the decimal value of
//the binary code converted from the gray code n.
int gray_to_binary(int n){
int binary = n;
while (n > 0){
n >>= 1;
binary ^= n;
}
return binary;
}
// Driver Code
int main(){
int n = 15;
cout<<"The decimal value of the binary code converted from the gray code is: ";
// Function call to convert gray code to binary code
cout << gray_to_binary(n) << endl;
return 0;
}
輸出
The decimal value of the binary code converted from the gray code is: 10
結論
本文解決了針對給定數字 n 查詢格雷碼及其逆的十進位制等價的問題。我們使用按位運算子解決了這個問題。為問題的兩個部分都提供了 C++ 程式。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP