I've tried several variations of sprintf() from this site and stackoverflow and continually to get the wrong value required. Can someone please explain why I'm not getting the desired result in MechAdd[1]??
Thanks.
byte MechAdd[1]; //Should be getting the value of 0x01 from sprintf() below
uint8_t sa[1]; //Correctly has the value of 1 created from another process
setup()
{
//--Convert sa[0] to HEX (0x01) and Set Global Variable
sprintf(MachAdd[1], "0x%2X", sa[0]);
delay(10);
Serial.println(MachAdd[1]); //What I'm getting is something other than the desired result, 0x01.
}
You've declared MachAdd[] as an array of size one (1) but are trying to jam at least 5 characters into it ("0xyy\0").
Enlarge the array to [10] (e.g.) and change your sprintf to:
sprintf( MachAdd, "0x%2X", sa[0] );
and your print to:
Serial.println( MachAdd );
Thank you, Blackfin. I noticed that I also had MachAdd declared as a byte, not char. My next would be, how can I pad those single digits with a leading "0" (ie 0-9)?? My current result is "0x 1".
peasoup:
Thank you, Blackfin. I noticed that I also had MachAdd declared as a byte, not char. My next would be, how can I pad those single digits with a leading "0" (ie 0-9)?? My current result is "0x 1".
That kind of thing can be done with field width specifiers, IIRC. The function has "everything but the kitchen sink" but that means you have a lot of documentation to go through to use all the features...
For quick reference you can use this formatting:
sprintf( MachAdd, "0x%02X", sa[0] );
Blackfin:
For quick reference you can use this formatting:
sprintf( MachAdd, "0x%02X", sa[0] );
I thought I tried that about 2 hours ago, but couldn't get it to work. I probably still had "byte MachAdd[1]" still set. Thanks for the second set of eyes on this.