I am using a keypad with IR receiver - the value when a key is pressed (0)=0x16.(1)=0xC etc
I wish to pad the input to two places and have it shown as 00, 01 - 99
Can anyone help with the coding please.
if (value < 10)
Serial.print('0'); // Add leading zero
Serial.print(value);
Thanks for the quick reply - I am not sure how that would convert and pad value.
could you give me a clearer idea.
if value = 0xC then result= ????
it’s Hex representation of …
0123456789ABCDEF …
12
@dolittle, the idea is not to change the variable itself, but only add the zero when displaying that value.
This is what johnwasser did, I put both decimal and hexadecimal in there:
void setup()
{
Serial.begin( 115200);
}
void loop()
{
int key = random( 0, 25);
// ------------------------------------------------
// Print as decimal
// ------------------------------------------------
// Value is 10 or above ? No leading zero
// Value is 9 or below ? Add leading zero
if( key < 10)
{
Serial.print( "0"); // Add leading zero
}
Serial.print( key, DEC);
// ------------------------------------------------
// Print as hexadecimal
// ------------------------------------------------
// Value is 0x10 or above ? No leading zero
// Value is 0x9 or below ? Add leading zero
Serial.print( " 0x");
if( key < 0x10)
{
Serial.print( "0");
}
Serial.print( key, HEX);
Serial.println();
delay( 500);
}
Try this sketch in Wokwi:
[ADDED] Updated the sketch in Wokwi. Added the printf() as shown by @groundFungus but made it safer.
Using the sprintf() function.
int numberA = 7;
int numberB = 0xc;
void setup()
{
Serial.begin(115200);
char numAstr[5];
char numBstr[5];
sprintf(numAstr,"%02d", numberA);
Serial.print("number A = ");
Serial.print("0X");
Serial.println(numAstr);
sprintf(numBstr,"%02X", numberB);
Serial.print("number B = ");
Serial.print("0X");
Serial.println(numBstr);
}
void loop()
{
}
Output:
number A = 0X07
number B = 0X0C
It was not clear that you wanted the result in hexadecimal.
if (value < 0x10)
Serial.print('0'); // Add leading zero
Serial.print(value, HEX);
Sorry for not explaining myself better - something along this line: I know its not correct but this is what I am looking for
String doConvert(HEX value) {
string result ;
if (value < 0x10)
result = '0'+ 'what';
else
result =' what';
return result;
}
The return should be two characters 01,02,03,04 etc
String doConvert(int value)
{
String result ;
if (value < 0x10)
result = '0' + String(value, HEX);
else
result = String(value, HEX);
return result;
}
perfect - thank you
Nice to see you came up with own solution
Thanks for pointing that out, seems to be floppy fingers.