Hi guys,
So i wrote a little code, not fancy, to convert a signed decimal to its binary representation using two complements.

``````char immeStr[17];

int main(){
int neg = 0;
int i = 0;
int bit = 6;
char binaryNum[bit+1];
int z1[bit+1];
int temp = -30;
int k;
int cout = 0;
char str[17];

memset(immeStr,0,17);

if(temp < 0){
temp = -temp;
neg =1;}

while(temp!=0){
z1[i]= temp % 2;
temp = temp / 2;
i++;
}
for(k = bit-1;k>=0;k--){
binaryNum[k] = z1[bit-1-k] +'0';
}

/*perform 2's complements*/
if(neg==1){
for(k = 0;k <bit;k++){
if(binaryNum[k] == '1'){
//printf("true %i, ",k);
binaryNum[k] = '0';
}else{
binaryNum[k] ='1';}
}

for(k = bit-1;k>=0;k--){
if(cout == 1){
if(binaryNum[k] == '0'){
binaryNum[k] = '1';break;
}else{
binaryNum[k] = '0';
cout = 1;
continue;}
}
if(binaryNum[k] == '0'){
binaryNum[k] = '1';break;
}else{
binaryNum[k] = '0';
cout = 1;}

}
}
strcpy(immeStr,binaryNum);
printf("%s\n",immeStr);

}[/code]
``````

I ran into a little problem displaying it as I increase the bit value. It works fine with 6 bits, from 7 up, it display weird thing
here are those weird things (they all suppose to represent # 30)
[code]at bit = 6 output >>> "011110"
at bit = 7 output >>> "P011110"
at bit = 10 output >>> "0000011110@"
at bit = 12 output >>> "0000�p011110"[/code]
You're not closing `binaryNum` as a string, so garbage gets copied into `immeStr`. Change the definition to this for a simple solution:
``````char binaryNum[bit+1] = {0};