- #include <iostream>
- #include <cstdlib>
- #include <string>
- std::string BinStr2BitStream(const std::string &charBinStr)
- {
- if ( charBinStr.size()%8 != 0 )
- {
- return "";
- }
- const int buffersize = (sizeof(unsigned char) * charBinStr.size()/8) + 1;
- unsigned char* pHexCharAscII = (unsigned char*)malloc(buffersize);
- if ( NULL == pHexCharAscII)
- {
- return "";
- }
- unsigned char* pHead = pHexCharAscII;
- memset(pHexCharAscII, 0, buffersize);
- unsigned char low4bit = 0;
- unsigned char high4bit = 0;
- std::string strBinStream = "";
- std::string::const_iterator pos = charBinStr.begin();
- unsigned char sum = 0;
- bool bLowbit = true;
- int iStep = 0;
- while ( pos != charBinStr.end() )
- {
- for ( int i = 3; i >= 0; --i )
- {
- sum += ((*pos) - 0x30) * ((unsigned char)0x1 << i);
- ++pos;
- }
- if ( bLowbit )
- {
- low4bit = sum;
- }
- else
- {
- high4bit = sum;
- }
- (*pHexCharAscII) ^= (low4bit << 4);
- (*pHexCharAscII) ^= high4bit;
- ++iStep;
- if ( 0 == iStep%2 )
- {
- if ( strBinStream == "" )
- {
- strBinStream = *pHexCharAscII++;
- }
- else
- {
- strBinStream += *pHexCharAscII++;
- }
- }
- bLowbit = !bLowbit;
- sum = 0;
- low4bit = 0;
- high4bit = 0;
- }
- free(pHead);
- return strBinStream;
- }
- int main(int argc, char** argv)
- {
- std::string strBin = "010000010100001100110010";
- std::string strStream = BinStr2BitStream(strBin);
- std::cout << strStream << std::endl;
- system("pause");
- }
16进制转码流