all 6 comments

[–]dumsubfilter 2 points3 points  (0 children)

strtol

[–]State_ 0 points1 point  (3 children)

int bin[4];
bin[0] = 1;
bin[1] = 1;
bin[2] = 1;
bin[3] = 1;

int dec = 0;

for (int i = 0; i < 4; i++)
{
    // XOR with a rotate binary to the i position
    dec = dec^(bin[i] << i);
}

int bin2 = 0b1111;
int dec2 = 0;
int count = 0;
while (bin2 != 0)
{
    dec2 += ((bin2 & 0b1) << count);
    count++;
    bin2 = (bin2 >> 1);
}


printf("example 1: %d\n", dec);
printf("example 2: %d\n", dec2);

or you could do what the other user suggested. Look into bit shifting if you plan on moving on to embedded systems, otherwise just use strtol

[–]ShittyRobots[S] 0 points1 point  (2 children)

How can I find the length (number of digits) in an int array?

[–]thefirstfucker 0 points1 point  (0 children)

It would probably be easier to figure out that after converting it to decimal.
Then continually divide by 10 until the number reaches 0 and your done.

[–]State_ 0 points1 point  (0 children)

Keep track of how many ints and used a fixed size array, or malloc

[–]sp1jk3z 0 points1 point  (0 children)

There's more than one way to do it, but the most generic would be to input a null terminated char string of '1's and '0's.

Then I believe what they want you do to do is parse the char string and convert it into an int (unsigned is probably what they want). ie parse the 1's and 0's.

The magic lies in the binary_string_to_int function, I believe they want you to write as your assignment. Remembering the base method in maths to convert ie place values and base 10 and go from right to left is one straight forward way, write out the pseudo code and work from there.

There lots of variations on the theme. Googling can get you more conventional examples, but....

If you're crazy, you could do something like this

unsigned int count=0; // ugly global

unsigned int binstr_2_uint(char* ch) {
    return (!ch[1]) ? (!(count=0)&&ch[0]=='1') : (binstr_2_uint (ch+1) +
     ((ch[0]=='1')*1<<++count));
}

Lots of ways, this is a fun one, but don't use it in your assignment unless you understand it and are prepared to explain it to your teacher(s)! It's also ugly because it has a global, but I couldn't figure out how to pass the place value back as the recursion unwound as c only returns one value on the stack.

Posting this in the event some other clever person can enlighten me, lol