二进制转BCD码

来源:互联网 发布:管理者心态管理知乎 编辑:程序博客网 时间:2024/05/22 14:11

二进制转BCD码, 进而可以转为十进制字符串表示.

这里采用"移位加三"方法, 也叫"Double Dabble 算法".  https://en.wikipedia.org/wiki/Double_dabble 

template<size_t _BITS>std::vector<unsigned char> bcd( const std::bitset<_BITS>& bits ){    std::vector<unsigned char> buf;    buf.push_back( 0 );    for( auto i = bits.size(); i-- != 0; )    {        int carries0 = bits.test( i ) ? 1 : 0;        for( auto& n : buf )        {            if( ( n & 0xf0 ) >= 0x50 )            {                n += 0x30;            }            if( ( n & 0x0f ) >= 5 )            {                n += 3;            }            int carries1 = n > 127 ? 1 : 0;            n <<= 1;            n |= carries0;            carries0 = carries1;        }        if( carries0 != 0 )        {            buf.push_back( 1 );        }    }    return buf;}


0 0
原创粉丝点击