我编写了这个程序来将二进制转换成十六进制,它忽略了二进制数字之间的其他字符。我想收到关于如何改进它的任何建议。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char table[] = "0123456789abcdef";
int main(int argc, char* argv[])
{
int flip = argc - 2;
unsigned char* ubin = argv[1];
unsigned int nibble = 0;
int i = 0;
int nothing = 1;
if((argc != 2) && (argc != 3 || strcmp(argv[2], "-f") != 0)){
fprintf(stderr, "Usage: %s 00001111 [-f]\n", argv[0]);
return EXIT_FAILURE;
}
printf("%s", "0x");
while(*ubin){
if((*ubin != '0') && (*ubin != '1')){
++ubin;
continue;
}
nibble <<= 1;
nibble |= *ubin - '0';
if(++i == 4){
i = 0;
if(flip)
nibble = ~nibble & 0xf;
putchar(table[nibble]);
nibble = 0;
nothing = 0;
}
++ubin;
}
if(nothing)
putchar('0');
putchar('\n');
if(i)
fprintf(stderr, "Error: %d bits were discarded, min unit is a nibble\n", i);
return 0;
}发布于 2016-05-02 21:49:33
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char table[] = "0123456789abcdef";这个常数应该是static const char table[]。作为一般规则,它不会与其他文件中的其他变量发生冲突,这些变量也称为table。
int main(int argc, char* argv[])
{
int flip = argc - 2;
unsigned char* ubin = argv[1];在对其进行距离检查之前使用argc和argv通常是危险的。在这种情况下,它可以工作,但这意味着ubin在这里可以是NULL。这段代码看上去可疑。
unsigned int nibble = 0;
int i = 0;坏变量名i。它应该是nbits,因为它包含当前咬口中的位数。
int nothing = 1;
if((argc != 2) && (argc != 3 || strcmp(argv[2], "-f") != 0)){
fprintf(stderr, "Usage: %s 00001111 [-f]\n", argv[0]);
return EXIT_FAILURE;
}
printf("%s", "0x");一个简单的printf("0x")就更清晰了。
while(*ubin){而不是这个while循环,而是编写一个for循环:for (ubin = argv[1]; *ubin != '\0'; ubin++) {。然后您就不需要多次编写ubin++了。
if((*ubin != '0') && (*ubin != '1')){
++ubin;
continue;
}
nibble <<= 1;
nibble |= *ubin - '0';
if(++i == 4){
i = 0;
if(flip)
nibble = ~nibble & 0xf;另一种选择是nibble ^= 0xf;。
putchar(table[nibble]);
nibble = 0;
nothing = 0;
}
++ubin;
}
if(nothing)
putchar('0');
putchar('\n');
if(i)
fprintf(stderr, "Error: %d bits were discarded, min unit is a nibble\n", i);如果出现错误,返回值应该是EXIT_FAILURE,而不是0。
return 0;
}但除了所有这些评论外,这个节目看上去还不错。你做了正确和严格的论证检查。当程序获得更多选项时,应该考虑使用getopt库来解析命令行。但就目前而言,一切都很好。
在剩下的参数之后有选项是不寻常的;-f 00001111比00001111 -f更常见。
主要算法简洁简洁。我特别喜欢最后的错误处理。有太多的其他程序就是不这么做的。
https://codereview.stackexchange.com/questions/127335
复制相似问题