Hi all, I am a beginner C programmer and I'm currently practicing on Linux environment with a series of programming exercises. I'm struggling with a program that doesn't work. It is meant just as an exercise to take in input a binary number (as a string) and calculates the negative binary value through two complement:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int nbit, i=0;
printf("Enter the length of your binary number in bits: ");
scanf("%d", &nbit);
if(nbit<=0) {
fprintf(stderr, "Error: invalid input null value\n");
exit(1);
}
char number[nbit+1];
char rnumber[nbit+1];
printf("Enter the binary number: ");
scanf("%s", number);
for(int k=0; k<nbit; k++) {
if(number[k]=='1')
number[k]='0';
else
number[k]='1';
}
printf("%s\n", number);
for(int j=nbit-1; j>=0; j--)
rnumber[i++]=number[j];
printf("%s\n", rnumber);
exit(0);
}
I feel I'm missing something, but I don't know what. Anyway, it's just a debug version and I'm aware that I should add 1 after executing the "NOT" operation for every character. I've reversed the original string (from big-endian to little-endian format), because I should also output the corresponding decimal value later. Hope you can help me to figure out what it's wrong. This is the output that I get:
1 2 3 4 5 6
rootzu@System:~/rootzu/C_Lab/Exercises$ ./complement_two
Enter the length of your binary number in bits: 8
Enter the binary number: 00001111
11110000
00001111 $x�1�ġп
Ok, fixed. I am a disaster. I forgot to insert the null character at the end of rnumber[]. Now it works, so I can implement the code to add 1 and calculate the corresponding decimal value.
Yes, I had written previously in my original post that it was just a debug version and that the add 1 part it was not included. I had also figured out that the null character was the problem. I actually posted my reply before reading yours. Anyway, thank you Disch, now I can complete my program :)