aboutsummaryrefslogtreecommitdiffstats
path: root/7_1/main.c
blob: 0c9ae143a98882a6ba2c5524b001ea99cfe93fd3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include<stdlib.h>
#include<stdio.h>

#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 <number>\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;
}