Serial Print negative numbers in Binary form

I was curious why printing negative numbers in binary results in output that far exceeds the size of an int data type. With this code:

void setup()
{
 Serial.begin(115200);
 int a = -1;
 Serial.print("A = ");
 Serial.println(a);
 Serial.print("A = ");
 Serial.print(a,BIN);
 Serial.println(" in Binary");

 
 
}

void loop()
{}

I get this output:

A = -1
A = 11111111111111111111111111111111 in Binary

What is happening here?

Negative number in Binary are in 2's complement form

So -1 =

Binary of 1 say in 16bits =

00000000000000001

  • 1
    to form 2 comp[lement = 1111111111111111.

Remember the 2'complement of a numbe = Binary of positive number then add 1

so -1 = 11111111111111111

  • 2 = 11111111111111110

I would have expected to see 16 1's in a row to represent a -1 in an int data type. What printed was 32 1's in a row. This is what gets printed with -2.

a = 11111111111111111111111111111110

This is on an Arduino mega2560

jerseyguy1996:
I would have expected to see 16 1's in a row to represent a -1 in an int data type. What printed was 32 1's in a row. This is what gets printed with -2.

a = 11111111111111111111111111111110

This is on an Arduino mega2560

It does not matter what size the data is the 2's complement is always the positve + 1

in 8,16 ,24 , 32 wtc., its just the format - 1 is alway a string if 1's

Useually the hex format ids used

  • 1 in 8 buts = FF
    -1 in 16 bits = FFFF
    -1 in 24 bits = FFFFFF
    -1 in 32 biss = FFFFFFFF

Any other size will be exntened to pacxk FF into the upper order.

What printed was 32 1's in a row

What this means is that Serial.print is treating "-1" as an unsigned long (32 bit) integer.

You have the source, so checking how the function overloads work is easy.

.print(int) just calls .print(long). This causes a sign extension to 32 bits which is a problem in BIN and HEX formats. If you cast the value to 'unsigned' it will call .print(unsigned) which will call .print(unsigned long) and therefore no sign extension.

Thank you everyone for the great explanations!

Unwashed solution, wrap word() around the negative number. eg. Serial.println(word(-1000), HEX);