Skip to content

Unexpected behaviour of print(char, HEX) and print(int, HEX) #66

@nharrand

Description

@nharrand
char c = 255;
Serial.print(c, HEX);

produces

FFFFFFFF

This is due to the fact that print(char c, int base) convert char c (1 byte) into an unsigned long (4 bytes). As char is signed 255 is in fact -1(Two's complement), once written in 4 bytes it becomes FFFFFFFF. But as a user I would rather have FF than FFFFFFFF.

The problem exist with int (2 bytes) too

Here is a more complete example:

void setup() {
  Serial.begin(9600);
  int i = 1;
  Serial.print("i: ");
  Serial.print(i, 10);
  Serial.print(" | ");
  Serial.println(i, HEX);
  i = -1;
  Serial.print("i: ");
  Serial.print(i, 10);
  Serial.print(" | ");
  Serial.println(i, HEX);

  char c = 127;
  Serial.print("c: ");
  Serial.print(c, 10);
  Serial.print(" | ");
  Serial.println(c, HEX);
  c = 255;
  Serial.print("c: ");
  Serial.print(c, 10);
  Serial.print(" | ");
  Serial.println(c, HEX);
}

void loop() {}

output

i: 1 | 1
i: -1 | FFFFFFFF
c: 127 | 7F
c: -1 | FFFFFFFF

where I owuld rather have

i: 1 | 1
i: -1 | FFFF
c: 127 | 7F
c: -1 | FF

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions