I am writing a library for RTC module in Arduino where the data is stored in BCD. I know how the Decimal number is converted into BCD but having some problem while writing it programmatically. After searching the internet I got two formulas which are as follows and working perfectly but cannot understand how it is calculating.
1. Formula1
DEC to BCD
(value / 10 * 16) + (value % 10)
Example
DEC -> 40 which converted to 01000000 in BCD which is again equal to 64.
So if I put into the formula I get the same result.
(40/10 * 16) + (40%10)
= (4*16) + 0
= 64
BCD to DEC
(value / 16 * 10) + (value % 16)
2. Formula2
DEC to BCD
val + 6 * (val / 10)
BCD to DEC
val - 6 * (val >> 4)
If anyone can explain it in details it will be helpful.
Thanks to all in advance.