Skip to content

Serial.print as HEX should ALWAYS print 2 chars per byte; it omits leading zeroes [imported] #40

@cmaglie

Description

@cmaglie

This is Issue 1097 moved from a Google Code project.
Added by 2012-11-05T10:22:49.000Z by dale.cal...@gmail.com.
Please review that bug for more context and additional comments, but update this bug.

Original labels: Type-Defect, Priority-Medium

Original description

What steps will reproduce the problem?
1.If byte or integer variables are printed with serial.print or serial.println with the HEX output format option leading zeroes are not printed:
byte reading5 = 0x0F;
byte reading6 = 0x00;
byte reading7 = 0xF0;
.............
Serial.print("reading5 = ");
Serial.println(reading5, HEX);
Serial.print("reading6 = ");
Serial.println(reading6, HEX);
Serial.print("reading7 = ");
Serial.println(reading7, HEX);


and the result is:
reading5 = F
reading6 = 0
reading7 = F0

What is the expected output? What do you see instead?

The output for HEX should always be one char per nibble; leading zeroes matter. With the data above, calling:
Serial.print("0x");
Serial.print(reading5, HEX);
Serial.print(reading6, HEX);
Serial.println(reading7, HEX);

yields 0xF0FO where it should display 0x0F00FO; the value is totally changed by omission of the leading zero.

What version of the Arduino software are you using? On what operating
system? Which Arduino board are you using?
Arduino 1.0.1, WinXP (current, fully updated), Duemilinove

Please provide any additional information below.

Same behaviour with Arduino 1.0 and using the Arduino serial monitor or SecureCRT interface.

I can't think of any reason to omit leading zeroes when using the HEX format. In cases like this, where a sequence of bytes is read from a device that represents a multi-byte return value, and you want to see the real value returned it gives incorrect results. One could assemble the bytes into a LONG and then call the function, but I think that most who use the HEX format would like to see all their nibble values with any size data. The examples in the Arduino reference sidestep the issue by not showing any example with a leading zero ;-)
http://arduino.cc/en/Serial/Print

Metadata

Metadata

Assignees

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