I am doing Arithmetic Coding now, and I have got the final start position and distance, then I add them.
How can I convert the result to binary mode?
For example, how can I convert 0.125 decimal to 0.001 binary in C++?
void CArithmeticCoding::Encode()
{
if ( 0 == m_input )
return;
printf("The input is [%s].\n", this->m_input);
while (*m_input)
{
if ( *m_input == m_MPS )
{
DOMPS();
}
else
{
DOLPS();
}
++m_input;
}
double ret = m_start + m_dis;
return;
}
Converting anything to binary means finding out how many of each kind of power of 2 is involved. In the case of a decimal number, the powers involved are negative.
For
.125, the sequence is like this:So, the binary representation is
0x2^-1+0x2^-2+1x2^-3=.001binary. As an exercise, contrast this technique with converting a normal integer into binary representation.Just as regular decimals can have non-terminating patterns (like 1/3 or pi/4), the same can happen for the binary representations. In those cases, you have to stop the calculation when you reach your desired precision.