I'm writing a C program that takes in a num (decimal, hex, or octal) and converts it into two's complement binary form.
The algorithm should be right since I had use it elsewhere before but I am confused on how to return the array of int's of 0's and 1's.
My understanding is I have to use malloc to allocate the memory space for this new array but I'm not sure how to do it syntax-wise.
This is what I have so far:
char *itob (int num, int size) {
int binary[size];
binary[size] = (int *)malloc(size);
for (int i=0; i<size; i++) {
binary[i] = 0;
}
int decimal = num;
int counter = 0;
if (decimal > -32768 && decimal < 32767) {
if (decimal < 0) {
decimal = 65536 + decimal;
}
while (decimal>0) {
binary[counter] = decimal%2;
decimal = decimal/2;
counter++;
}
}
return binary;
}
The parameter num
is the number to convert and size
is the number of bits I want to print.