 # Confused with binary

Hi

I thought I had a good understanding of binary numbers up to now.

Then I saw this…now I am confused!!

``````Example Code
int a = 103;    // binary:  0000000001100111
int b = ~a;     // binary:  1111111110011000 = -104
``````

How does all that one’s only add up to dec 104?(except for the MSB bit which is the neg sign bit)

https://www.arduino.cc/reference/en/language/structure/bitwise-operators/bitwisenot/

It is interpreted as 28 16 - value.

See Two’s complement.

Ok...But what is the DEC Value of this binary number?

0111111110011000

I get.

DEC 32664

HEX 7F98

Above example this binary number is 104 this is the confusing part.

There are 2 types of integers, signed and unsigned.

For all signed integers the high/top bit is sign where if that bit is 1 the value is negative and if it's 0 the value is positive.
WHAT value? That's what the Twos Complement is about.

16 bit signed integers can count from -32768 to +32767.

For unsigned integers there is no sign bit.

16 bit unsigned integers can count from 0 to 65535.

If you subtract 16 bit unsigned 1111111110011000 (dec 65432) from unsigned 65536 you get 104 and the sign bit tells you iot is -104..

Bitmath Tutorial - use the power of bits to save cpu cycles and RAM.
https://playground.arduino.cc/Code/BitMath

Above example this binary number is 104 this is the confusing part.

It is decimal -104 as in 0 - 104 = -104.

Binary 104 is 0b1101000 and binary -104 is 0b1111111110011000.
Add the binary values in 32-bit integers and you get 0b10000000000000000, 1 bit higher than 16.

With unsigned integers we calculate TIME DIFFERENCES. If I subtract a start time from an end time, even if the end time is "rolled over" past 0 the answer will be right because of unsigned subtraction. it is like how between 10 and 2 on a round 12 hour clock is 4 hours -- from 2 backward for subtract 10 leaves us on 4, the hours between 10 and 2 as clock/unsigned 2 minus/backwards 10.

If only there was one extra line in the example showing the subtraction part ...HUH.

Thanks for the detail.

I used to have a sketch I'd drop for that one but I lost it in a 2015 crash.

This will have to do.

``````word startVal, endVal; // word is Arduino unsigned int

void setup()
{
Serial.begin( 115200 ); // set Serial Monitor to match

startVal = 60000;  // top value is 65535
endVal = 10000;    // 65535 - 60000 + 10000 = 15536

Serial.println();
Serial.println();
Serial.println( endVal - startVal ); // prints 15536

}

void loop() {
// put your main code here, to run repeatedly:

}
``````

Mess with it. Print the values in BIN, start/end/difference.

If you can work with generalities then work out unsigned subtraction using 4 bit values, there's less to get wrong.