描述

十进制 二进制 格雷码
0 0000 0000
1 0001 0001
2 0010 0011
3 0011 0010
4 0100 0110
5 0101 0111
6 0110 0101
7 0111 0100
8 1000 1100
9 1001 1101
10 1010 1111
11 1011 1110
12 1100 1010
13 1101 1011
14 1110 1001
15 1111 1000

输入

7
1010

输出

数值7对应的格雷码
格雷码1010转化为二进制数的十进制值

c++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <vector>
#include <bitset>
using namespace std;
vector<unsigned long> gray(int n)
{
vector<unsigned long> res;
for (unsigned long i=0; i<(1<<n); i++)
res.push_back(i^(i>>1));
return res;
}
int toGray(int x){//转化为格雷码
return x^(x>>1);
}
int toBinary(int x){//格雷码转化为二进制
int y = x;
while(x>>=1){
y ^= x;
}
return y;
}
int main()
{
vector<unsigned long> v=gray(4);
for (int i=0; i<v.size(); i++)
cout<<"i = "<<i<<"\t"<<bitset<4>(v[i])<<endl;
cout<<"get a number "<<endl;
int n;cin>>n;
cout<<"the gray is "<<bitset<8>(toGray(n))<<endl;
cout<<"get in a gray number "<<endl;
char s[10];cin>>s;
int tmp,num=0;
n=strlen(s);tmp=1<<(n-1);
for(int i=0 ; i<n ; i++){
if(s[i]=='1')num+=tmp;
tmp>>=1;
}
cout<<"to b num = "<<toBinary(num)<<endl;
return 0;
}