#include #include #define RED "\x1b[91m" #define GRN "\x1b[92m" #define RST "\x1b[0m" /* breaks (segfaults) if x = 0x8000000000000000 */ char* tobin(long int x) { size_t i = 0, j = 0; char buffer[64]; char *ret; char sgn = x < 0; x *= ((x > 0) << 1) - 1; /* Negate the number without if statement */ for (; x; x >>= 1) buffer[i++] = '0' + (x & 1); /* Write the bits to the buffer */ ret = calloc(i + 1 + sgn, sizeof *ret); /* Allocate an arary for the number */ ret[0] = '-'; /* Always write minus as the first sign*/ j += sgn; /* If sign is negative, increment j so that '-' is not overwritten */ while (i) ret[j++] = buffer[--i]; /* reverse copy buffer into ret */ return ret; } int main(int argc, char* argv[]) { long number; char *bin; if (argc != 2) { fprintf(stderr, RED "Error: Invalid amount of arguments\n" RST "Usage: " GRN "%s \n" RST , argv[0]); return EXIT_FAILURE; } number = atol(argv[1]); /* Since I am negating a number using the branchless trick, * Multiplying this number by -1 still gives you a negative number because of the overflow * Unfortunately this has to be handled separately */ if (number == 0x8000000000000000) { puts(RED "Error: " RST "The number does not fit in 64 bits"); return EXIT_FAILURE; } bin = tobin(number); printf("Binary for %-20li: %s\n", number, bin); free(bin); return EXIT_SUCCESS; }