Go Down

Topic: Printing negative ints, why four bytes (Read 333 times) previous topic - next topic

michinyon

So this code
Code: [Select]
#include <Arduino.h>

void setup()
{  Serial.begin(9600);
  int i=1 ;
  int j=-1 ;
  Serial.println(i);
  Serial.println(j);
  Serial.println(i,HEX);
  Serial.println(j,HEX);
}
void loop()
{
}


Prints this
Quote

1
-1
1
FFFFFFFF


Now if the int is 16 bits,  should be four hex digits.  So why do I get 8 hex digits ?

If I change "i" to some positive number like 512,  I get 200 hex.



majenko

Because the function Serial.print casts the incoming value to a long, and -1 in long is 0xFFFFFFFF.

robtillaart

Quote
Because the function Serial.print casts the incoming value to a long, and -1 in long is 0xFFFFFFFF.


yep it is in the Print library code

size_t Print::print(int n, int base)
{
  return print((long) n, base);
}

you would get the same effect when you used a   char j = -1;
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy