Originally Posted by

**MrWannabe**
Most of these are more binary math-related problems rather than c problems, so it seems to make most sense to find the way to convert it with those limited 9 operations first before putting it in c.

You might as well just work in C; the bit operators are all transparent so it is like using a calculator.

Here is a partial solution to #1 which illustrates a use of two's compliment. It only works on positive numbers.

Code:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int x=1<<(sizeof(int)*8-1), y=x-1, z;
printf("Lowest int: %d Highest int: %d\n",x,y);
if (argc<2) {
puts("Need a number");
return 0;
} else z=atoi(argv[1]);
z^=y; z|=x; z+=1;
printf("%d",z);
return 0;
}

The line in red reveals the lowest and highest signed int values using two's compliment, which these are useful masks since the lowest one is this (for simplicity, I'm using a char scale, 8 bits):

10000000

Only the __M__ost __S__ignificant __B__it set, which is the sign. Unfortunately, you cannot just OR this with a positive number, since negative values proceed in reverse (-1 is 11111111). First, you must flip all but the MSB by using the highest int value, 01111111. In fact, this will be the lowest value minus 1, since the value cannot get any lower, it "wraps around" and becomes the highest positive value instead*.

This comes out as one less than the negative value, so we add 1 to it.

**[root~/C] ./a.out 92345973**

Lowest int: -2147483648 Highest int: 2147483647

-92345973

I should maybe clarify that by "using two's compliment" here I did not mean using the actual formula, ("*The two's complement of a binary number is defined as the value obtained by subtracting the number from a large power of two (specifically, from 2N for an N-bit two's complement*") since you cannot use subtraction. I meant using "an awareness" of how a two's compliment number is stored in a computer (as a signed value).

Anyway, I am sure you will want those two masks for something

* you can also get that number using XOR, obviously, which might be better since you're not suppose to use subtraction.