arduino / arduino/ArduinoCore-API

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

Open
#66 6 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
306
Forks
150
PR merge metrics
No merged PRs in 30d

Description

```
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
```

Contributor guide

No contributing guide indexed for this repository

Research direction

Start by locating the Serial.print(char c, int base) and Serial.print(int, int base) overloads described in the issue, then run the complete example sketch to reproduce the output. Done means hexadecimal output uses the operand's width, producing FFFF for -1 as an int and FF for -1 as a char, while preserving the existing decimal output.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
api, embedded-iot
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.