/* //该程序生成n位的格雷码 */ #include <iostream> using namespace std; #define MAX_BIT 20 unsigned int n; //把十进制数转化成对应的二进制
void deciTobinary(unsigned int num, char *str) { unsigned int stack[MAX_BIT]; int top = -1; while (num) { stack[++top] = num % 2; num = num / 2; } str[n] = '\0'; int k = n; for (int i = 0; i <= top; i++) { str[--k] = stack[i] + '0'; } for (k = k -1; k >= 0; k--) str[k] = '0'; } void main () { char str[MAX_BIT]; cout << "please input the binary bits greycode:" <<endl; cin >> n; for (unsigned int i = 0; i < (1 << n); i++) { unsigned int tempNum = (i ^ (i << 1)) >> 1; if (tempNum == 0) // 为0,则直接输出
{ for (int j = 0;j < 5; j++) printf("%c",'0'); printf("\t"); } else { deciTobinary(tempNum, str); printf("%s\t", str); } } }
|
//生成所有5位的格雷码如下:
00000 00001 00011 00010 00110 00111 00101 00100 01100 01101 01111 01110 01010 01011
01001 01000 11000 11001 11011 11010 11110 11111 11101 11100 10100 10101 10111 10110
10010 10011 10001 10000
阅读(926) | 评论(0) | 转发(0) |