# Challenge - Number conversion using binary manipulation

Problem:

I have a sensor with a range of 0 to 4095.
I need my output to be 4095 to 0.

Solution:

``````(sensor output - 4095 = output);
//Since the result is negative (0-4095 = -4095)  calculate the "modulus" to make it positive
output = |output|;
``````

Question:
Can the above be achieved using binary manipulation instead?

Can the above be achieved using binary manipulation instead?

Arithmetic is "binary manipulation"
Google "two's complement"

Reverse the subtraction.

``````output = 4095 - sensor_output;
``````

And assuming that "binary manipulation" means logical operators, it is difficult to do arithmetic because you have to handle all the borrowing and carrying yourself.

``````output = sensor_output ^ 4095;
``````

PaulRB:

``````output = sensor_output ^ 4095;
``````

You missed the sneaky "+ 1"

AWOL:

PaulRB:

``````output = sensor_output ^ 4095;
``````

You missed the sneaky "+ 1"

Cool. So in machine code this is more efficient than using a subtraction, right?
Does the uC actually use 2's complement internally to do the subtraction? Any way I could have access to that as with other logical operators?

Any way I could have access to that as with other logical operators?

Yes, C supports the operators "+" and "-"

AWOL:

``````output = sensor_output ^ 4095;
``````

Nope. Works fine when the input is small, but going to higher numbers the result is 5000 or 6000.

Example, when the sensor value is 1024 the output is 5120.

AWOL:

Any way I could have access to that as with other logical operators?

Yes, C supports the operators "+" and "-"

No, I meant the 2's complement result.

Example, when the sensor value is 1024 the output is 5120

?

casemod:
Cool. So in machine code this is more efficient than using a subtraction, right?
Does the uC actually use 2's complement internally to do the subtraction? Any way I could have access to that as with other logical operators?

Addition and subtraction are just as efficient as any of the logical operators, multiply and divide are different stories.