Pages: [1]   Go Down
Author Topic: Printing negative ints, why four bytes  (Read 287 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Faraday Member
**
Karma: 62
Posts: 3077
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: 100
Posts: 4153
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

Get 10% off all 4D Systems TFT screens this month: use discount code MAJENKO10

Global Moderator
Netherlands
Online Online
Shannon Member
*****
Karma: 220
Posts: 13839
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: