33,027
社区成员




#include <string>
#include <iostream>
#include <bitset>
#include <algorithm>
#include <map>
using namespace std;
typedef unsigned int uint;
map< char, uint > g_mapEncode;
map< uint, char > g_mapDecode;
const uint g_cnMaxBits = 512;
void Encode( const string &strData, string &strOut )
{
uint nNum = 0, nCurBit, nEndBit;
bitset<g_cnMaxBits> bsResult;
string::const_iterator iCurNum;
for ( nCurBit = 0, iCurNum = strData.begin();
iCurNum < strData.end(); ++iCurNum, ++nCurBit )
for ( uint j = 0; j < g_mapEncode[ *iCurNum ]; ++j )
bsResult.flip( nCurBit++ );
nEndBit = nCurBit;
for ( strOut.clear(), nCurBit = 0; nCurBit < nEndBit; nNum = 0 )
{
for ( uint j = 0; j < 4 && nCurBit < nEndBit; ++j )
nNum |= ( uint( bsResult[nCurBit++] ) << j );
strOut.push_back( nNum + ( ( nNum < 10 ) ? '0' : ( 'A' - 10 ) ) );
}
for ( iCurNum = strOut.end() - 1;
iCurNum >= strOut.begin() && *iCurNum == '0'; --iCurNum );
strOut.erase( iCurNum + 1, strOut.end() );
}
void Decode( const string &strData, string &strOut )
{
const uint cnMaxBits = 512;
uint nEndBit, nNum, nCurBit = 0, nLastNum = 0;
bitset<g_cnMaxBits> bsResult;
string::const_iterator iCurNum;
for ( iCurNum = strData.begin(); iCurNum < strData.end(); ++iCurNum )
{
nNum = *iCurNum - ( ( *iCurNum >= 'A' ) ? 'A' - 10 : '0' );
for ( int j = 0; j < 4; ++j, nNum >>= 1 )
bsResult.set( nCurBit++, ( nNum & 1 ) == 1 );
}
nEndBit = nCurBit;
for ( strOut.clear(), nCurBit = 0; nCurBit <= nEndBit; ++nCurBit )
if ( !bsResult.test( nCurBit ) )
{
strOut.push_back( g_mapDecode[ nCurBit - nLastNum ] );
nLastNum = nCurBit + 1;
}
strOut.resize( 81, '.' );
}
void main( int argc, char* argv[] )
{
int nIndex = 0;
g_mapEncode.insert( pair< char, uint >( '.', nIndex++ ) );
g_mapEncode.insert( pair< char, uint >( '9', nIndex++ ) );
g_mapEncode.insert( pair< char, uint >( '8', nIndex++ ) );
g_mapEncode.insert( pair< char, uint >( '7', nIndex++ ) );
g_mapEncode.insert( pair< char, uint >( '2', nIndex++ ) );
g_mapEncode.insert( pair< char, uint >( '3', nIndex++ ) );
g_mapEncode.insert( pair< char, uint >( '1', nIndex++ ) );
g_mapEncode.insert( pair< char, uint >( '5', nIndex++ ) );
g_mapEncode.insert( pair< char, uint >( '6', nIndex++ ) );
g_mapEncode.insert( pair< char, uint >( '4', nIndex++ ) );
g_mapEncode.insert( pair< char, uint >( '0', nIndex++ ) );
for ( map< char, uint >::iterator cur = g_mapEncode.begin();
cur != g_mapEncode.end(); ++cur )
{
g_mapDecode.insert( pair<int, char>( cur->second, cur->first ) );
}
string strAll;
strAll = "....76.2."\
".7.98..15"\
".....59.."\
"....6..8."\
"9.......6"\
"..2.1..37"\
".8..9...2"\
".37..1..."\
".5.......";
string strOut;
Encode( strAll, strOut );
cout << "Encode(" << strOut.length() << "): " << strOut << endl;
Decode( strOut, strAll );
cout << "Decode: " << strAll << endl;
system( "pause" );
}