gpt4 book ai didi

c - 尝试将二进制转换为格雷码

转载 作者:行者123 更新时间:2023-11-30 21:01:45 25 4
gpt4 key购买 nike

我试图将二进制转换为格雷码,但我不知道这段代码有什么问题:

#include <stdio.h>

// I copied this function from wiki
unsigned int binaryToGray(unsigned int num) {
return num ^ (num >> 1);
}

int main(int argc, const char *argv[]) {
unsigned int binarynum = 10;
unsigned num = binaryToGray(binarynum);
printf("%d!!", num);
return 0;
}

最佳答案

为了了解格雷码的工作原理,请添加一个将数字转换为其二进制表示形式的函数:

#include <stdio.h>

char *numtobin(char *buf, unsigned int num) {
char temp[65], *p = buf + sizeof(buf);

*--p = '\0';
while (num >= 2) {
*--p = '0' + (num & 1);
num >>= 1;
}
*--p = '0' + num;
return strcpy(buf, temp);
}

// I copied this function from wiki
unsigned int binaryToGray(unsigned int num) {
return num ^ (num >> 1);
}

int main(int argc, const char *argv[]) {
char buf1[65], buf2[65];
unsigned int num, greynum;

for (num = 0, num <= 32; num++) {
greynum = binaryToGray(num);
printf("%2d %6s -> %6s %-2d\n",
num, numtobin(buf1, num), numtobin(buf2, greynum), greynum);
}
return 0;
}

关于c - 尝试将二进制转换为格雷码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34466672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com