title: Another BCD byte[] to int and back again
body: <p>Im having trouble with some conversions, and can´t find whats wrong with the code,
  or with the idea of what it has to do.</p>
  
  <p>I have the following byte[]</p>
  
  <pre><code>byte[] bytes = {0xFF, 0xFF, 0xFE};
  </code></pre>
  
  <p>which I convert into ulong this way:</p>
  
  <pre><code>ulong next = ((uint)((((0x00 &lt;&lt; 4) | bytes[0]) &lt;&lt; 16) | ((bytes[1] &lt;&lt; 8) | bytes[2])));
  </code></pre>
  
  <p>next thing I add 1 to next:</p>
  
  <pre><code>next++;
  </code></pre>
  
  <p>Then, I want to convert the ulong, back to the byte array. I tryed with several bcd algorithms found here and on the web, but I cannot get the result I am expecting:</p>
  
  <pre><code>byte[] bytes = {0xFF, 0xFF, 0xFF};
  </code></pre>
  
  <p>insted of</p>
  
  <pre><code>{ 0x15, 0x72, 0x77, 0x16}
  </code></pre>
  
  <p>which I am getting with most of the solutions I have tryed.</p>
  
  <p>Here is one of the algorithms I have used:</p>
  
  <pre><code>static Byte[] CopyAsBCD(UInt32 value)
          {
              Byte[] buffer = new byte[4];
              Int32 offset = 0;
              var length = 4;
              var s = value.ToString();
              var stringIndex = s.Length - 1;
              var bufferIndex = offset + length - 1;
              var isLower = true;
  
              try
              {
                  while (bufferIndex &gt;= offset &amp;&amp; stringIndex &gt; -1)
                  {
  
                      if (isLower)
                          buffer[bufferIndex] = Byte.Parse(s[stringIndex].ToString());
                      else
                          buffer[bufferIndex] += (Byte)(Byte.Parse(s[stringIndex].ToString()) &lt;&lt; 4);
  
                      if (!isLower)
                          bufferIndex--;
                      isLower = !isLower;
                      stringIndex--;
                  }
  
              }
              catch
              {
              }
              return buffer;
          }
  </code></pre>
  
  <p>What I am doing wrong? or I have a concept problem?</p>