I wrote this program to convert binary to hex, it ignores other characters between the binary digits. I would like to receive any recommendations on how to improve it.
#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;
}