Two complement's program in C

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:

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
#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�ġп


What is that junk string at the end?

rootzu

Last edited on
1
2
    for(int j=nbit-1; j>=0; j--)
        rnumber[i++]=number[j];


You are bit-reversing the value (mirror image). IE: 12345 becomes 54321. This does not have anything to do with 2's complement.

Negating a value in 2's compliment can be done by:
1) Inverting all bits (which you are doing correctly)
2) then adding 1, which you are not doing


What is that junk string at the end?


You didn't give 'rnumber' a closing null character, so printf is printing past the end of the buffer and showing garbage data.
Last edited on
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.
Last edited on
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 :)
Topic archived. No new replies allowed.