Pages: [1]   Go Down
Author Topic: Printing negative ints, why four bytes  (Read 237 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Edison Member
*
Karma: 28
Posts: 2045
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

So this code
Code:
#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.


Logged

UK
Offline Offline
Faraday Member
**
Karma: 92
Posts: 3969
Where is your SSCCE?!?!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Why not visit my eBay shop? http://stores.ebay.co.uk/Majenko-Technologies
Replacement for the Arduino IDE: UECIDE - Proper serial terminal, graphing facilities, plugins, overhauled internals.
Java isn't bad in itself, but it has enabled morons to write programs.

Global Moderator
Netherlands
Offline Offline
Shannon Member
*****
Karma: 170
Posts: 12465
In theory there is no difference between theory and practice, however in practice there are many...
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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;
Logged

Rob Tillaart

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

Pages: [1]   Go Up
Jump to: