Pages: [1]   Go Down
Author Topic: Finding a leading zero  (Read 541 times)
0 Members and 1 Guest are viewing this topic.
Texas, USA
Offline Offline
Newbie
*
Karma: 0
Posts: 22
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Apart from using characters, is it possible to make a byte in HEX to show a leading 0?. I mean i.e. from zero to 0F I need to print 00..01....etc...0F. Thank you in advance.
Logged

France
Offline Offline
God Member
*****
Karma: 29
Posts: 898
Scientia potentia est.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Yes, it would be "%02X"

http://www.cplusplus.com/reference/clibrary/cstdio/printf/
Logged

Ontario
Offline Offline
God Member
*****
Karma: 20
Posts: 835
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Another job for sprintf().  Something like:

Code:
char buf[8];
sprintf(buf, "%04x", my_value);
Serial.println(buf);
Logged

Texas, USA
Offline Offline
Newbie
*
Karma: 0
Posts: 22
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thank you guix and gardner. I fixed my issue using:

Code:
char buf[8];
sprintf(buf, "%02x", my_value);
Serial.println(buf);
Logged

France
Offline Offline
God Member
*****
Karma: 29
Posts: 898
Scientia potentia est.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

No problem but use an upper case X if you want values such as "0F" instead of "0f", and buf[3] is enough, don't waste precious memory smiley
« Last Edit: October 10, 2012, 10:24:14 pm by guix » Logged

Global Moderator
UK
Offline Offline
Brattain Member
*****
Karma: 241
Posts: 24480
I don't think you connected the grounds, Dave.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
if (x < 16) {
  Serial.print ("0");
}
Serial.print (x, HEX);
Logged

"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

Pages: [1]   Go Up
Jump to: