In: Computer Science
A program called i2b.c was implemented with the intention to provide a binary representation of an integer. Unfortunately, the implementation has the following limitation:
Modify the existing source code of i2b.c such that:
PROGRAM BELOW
#include <stdio.h>
#define N 32
int main(int argc, char *argv[]) {
int n = 12345;
int binRep[N];
int i;
for (i = 0; i < N; i++) {
binRep[i] = 0;
}
i = 0;
while (n > 0) {
binRep[i] = n % 2;
n = n / 2;
i++;
}
for (i = N - 1; i >= 0; i--) {
printf("%d", binRep[i]);
}
printf("\n");
return 0;
}
// according to your code
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
int main(int argc, char *argv[]) 
{ 
    if (argc != 2){
        puts("usage: i2b <number>");
        return -1;
    }
    int32_t n = atoi(argv[1]);
    int binaryNum[32] = {}; 
    int i = 0; 
    
    while (n > 0 && i < 32) { 
        binaryNum[i] = n % 2; 
        n = n / 2; 
        i++;
    } 
    
    if(n >= 0){
        binaryNum[31]=0;
    } else {
        binaryNum[31]=1;
    }
    for (int i = 31; i > -1; i--){
        printf("%d", binaryNum[i]);
    }
    
    puts("");
    return 0; 
}
/*better implementation
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
int main(int argc, char *argv[]){ 
    if (argc != 2){
        puts("usage: i2b <number>");
        return -1;
    }
    int32_t number = atoi(argv[1]);
    for(int i = 31; i > -1; i--){
        printf("%d", (number >> i) & 1);
    }
    puts("");
    return 0;
}
*/