I'm having trouble replacing characters in my c string. I have a c string called bits initialized to a sixteen bit string of 0's and 1's. What I'm trying to do is convert the strings into their twos complement versions. What I've learned is a simple assignment such as
int twosComplement(int number,char *binary){
printf("searching for twos complement\n");
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++;
}
for(x=0;x<16;x++){
if(bits[x]=='0'){
*bits="a";
}
else{
strcat(bits,"1");
}
printf("%s\n",bits);
}
is illegial in C because bits is actually a pointer to the first character in the string so it complains about an assignment from integer to pointer without a cast.
The above is code for this function. The first part works correctly and creates the proper 16 bit representation of the positive number. In the next part, i want to look at each character of the string and replace with the alternate character. This code compiles but doesn't work because im concatenating. Also, I don't think it's reading properly what digit each character is .
This code compiles cleanly using GCC 4.8.2 on Mac OS X 10.9.1 Mavericks with the command line:
Source:
Output:
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 asstrcat()
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.Here's a much simpler implementation of what you're trying to do:
and outputs: