# Thread: simple array question

1. ## simple array question

Hi, i am trying am dealing with numbers in two's complement. If I pass a negative number to the function, it turns it into positive and works out its binary equivalent. The bit I am stuck on is writing a loop that will do the following: take the least significant bit from array1 (i.e. its last element) and copy it into array2; so it keeps on copying until it encounters first 1, and from then on all 1's are copied as 0's and vice versa, so, for example -25:
array1 -> array2
Code:
`11001 -> 00111`
this is the code that i have, the only thing that doesn't work is the loop if flag == 1, can anyone help:
Code:
```#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

void binary_converter (int number,int binary[32], int n)
{
int *data;
int temp[32];
data = (int*) calloc (n, sizeof (int));
int i, k = 0, remainder, flag = 0;

if (number < 0){
number = number * -1;
flag = 1;
}

for (i = 0; i < n; i++){
remainder = number % 2;
number = number / 2;
data[i] = remainder;
}

while (i >= 0){
binary[k++] = data[--i];
}

if (flag == 1){
while (k >= 0){
if (binary[k] != 1){
temp[k] = binary[k]; k--;
}else{
temp[k] = binary[k]; k--;
if (binary[k] == 1){
binary[k] = 0;
temp[k] = binary[k]; k--;
}else {
binary[k] = 1;
temp[k] = binary[k]; k--;
}
}
}
}
printf ("%d\n", k);
for (i = 0; i < 5; i++){
printf ("%d ", temp[i]);
}
printf ("\n");

}

int main (void)
{
int binary[32] = {0};
int i;
binary_converter (-3 binary, 5);
for (i = 0; i < 5; i++){
printf ("%d ", binary[i]);
}
printf ("\n");
return 0;
}```

2. is there something wrong with this bit of code?
Code:
`	binary_converter (-3 binary, 5);`
does this compile? have you used the debugger to insure you don't get past the "flag == 1" ?

Popular pages Recent additions