[Solved] Replacing a character in a c string


This code compiles cleanly using GCC 4.8.2 on Mac OS X 10.9.1 Mavericks with the command line:

gcc -O3 -g -std=c11 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes \
        -Wold-style-definition -Werror bits.c -o bits

Source:

#include <math.h>
#include <stdio.h>
#include <string.h>

extern int twosComplement(int number);

int twosComplement(int number)
{
    printf("searching for twos complement of %d\n", number);
    int temp = number * -1;
    if (temp < -32768)
        return 0;
    printf("%d\n", temp);
    char bits[17] = "";
    int i;
    int x = 0;
    int y;
    for (i = 15; i >= 0; i--)
    {
        y = pow(2, i);
        if (temp % y != temp)
        {
            temp = temp % y;
            strcat(bits, "1");
        }
        else
        {
            strcat(bits, "0");
        }
        printf("%s\n", bits);
        x++;
    }

    printf("One's complement:\n");
    for (x = 0; x < 16; x++)
    {
        if (bits[x] == '0')
            bits[x] = '1';
        else
            bits[x] = '0';
        printf("%s\n", bits);
    }
    return 0;
}

int main(void)
{
    twosComplement(23);
    return 0;
}

Output:

searching for twos complement of 23
-23
0
00
000
0000
00000
000000
0000000
00000000
000000000
0000000000
00000000000
000000000001
0000000000010
00000000000101
000000000001011
0000000000010111
One's complement:
1000000000010111
1100000000010111
1110000000010111
1111000000010111
1111100000010111
1111110000010111
1111111000010111
1111111100010111
1111111110010111
1111111111010111
1111111111110111
1111111111100111
1111111111101111
1111111111101011
1111111111101001
1111111111101000

You still have to implement the +1 part of two’s complement.

Be wary of using strcat() in a loop like this. It leads to quadratic runtime behaviour as strcat() has to skip over the previous content before adding the new character, so it skips 0+1+2+3+4+…N-1 characters, which is N(N-1)/2 bytes skipped in total.

4

solved Replacing a character in a c string