title: BCD to Decimal And Decimal to BCD
body: <p>I am writing a <strong>library</strong> for <strong>RTC module</strong> in <strong>Arduino</strong> 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.</p>
  
  <p><strong>1. Formula1</strong></p>
  
  <p><strong>DEC to BCD</strong></p>
  
  <pre><code>(value / 10 * 16) + (value % 10)
  </code></pre>
  
  <p><strong>Example</strong></p>
  
  <p><strong>DEC -> 40</strong> which converted to <strong>01000000</strong> in <strong>BCD</strong> which is again equal to 64.</p>
  
  <p>So if I put into the formula I get the same result.</p>
  
  <pre><code>(40/10 * 16) + (40%10)
  = (4*16) + 0
  = 64
  </code></pre>
  
  <p><strong>BCD to DEC</strong></p>
  
  <pre><code>(value / 16 * 10) + (value % 16)
  </code></pre>
  
  <p><strong>2. Formula2</strong></p>
  
  <p><strong>DEC to BCD</strong></p>
  
  <pre><code>val + 6 * (val / 10)
  </code></pre>
  
  <p><strong>BCD to DEC</strong></p>
  
  <pre><code>val - 6 * (val &gt;&gt; 4)
  </code></pre>
  
  <p>If anyone can explain it in details it will be helpful.</p>
  
  <p>Thanks to all in advance.</p>