现在的位置: 首页 > 综合 > 正文

二进制字符串转换成对应的二进制码流

2013年10月02日 ⁄ 综合 ⁄ 共 2328字 ⁄ 字号 评论关闭
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <string>
  4. std::string BinStr2BitStream(const std::string &charBinStr)
  5. {
  6.     if ( charBinStr.size()%8 != 0 )
  7.     {
  8.         return "";
  9.     }
  10.     const int buffersize = (sizeof(unsigned char) * charBinStr.size()/8) + 1;
  11.     unsigned char* pHexCharAscII = (unsigned char*)malloc(buffersize);
  12.     if ( NULL == pHexCharAscII)
  13.     {
  14.         return "";
  15.     }
  16.     unsigned char* pHead = pHexCharAscII;
  17.     memset(pHexCharAscII, 0, buffersize);
  18.     unsigned char low4bit  = 0;
  19.     unsigned char high4bit = 0;
  20.     std::string strBinStream = "";
  21.     
  22.     std::string::const_iterator pos = charBinStr.begin();
  23.     unsigned char sum = 0;
  24.     bool bLowbit = true;
  25.     int iStep = 0;
  26.     while ( pos != charBinStr.end() )
  27.     {
  28.         for ( int i = 3; i >= 0; --i )
  29.         {
  30.             sum += ((*pos) - 0x30) * ((unsigned char)0x1 << i);
  31.             ++pos;
  32.         }
  33.         
  34.         if ( bLowbit )
  35.         {
  36.             low4bit = sum;
  37.         } 
  38.         else
  39.         {
  40.             high4bit = sum;
  41.         }
  42.         (*pHexCharAscII) ^= (low4bit << 4);
  43.         (*pHexCharAscII) ^=  high4bit;
  44.         
  45.         ++iStep;
  46.         
  47.         if ( 0 == iStep%2 )
  48.         {
  49.             if ( strBinStream == "" )
  50.             {
  51.                 strBinStream = *pHexCharAscII++;
  52.             }
  53.             else
  54.             {
  55.                 strBinStream += *pHexCharAscII++;
  56.         }
  57.         }
  58.         
  59.         bLowbit = !bLowbit;
  60.         sum = 0;
  61.         low4bit = 0;
  62.         high4bit = 0;
  63.     }
  64.     free(pHead);
  65.     return strBinStream;
  66. }
  67. int main(int argc, char** argv)
  68. {
  69.     std::string strBin = "010000010100001100110010";
  70.     std::string strStream = BinStr2BitStream(strBin);
  71.     std::cout << strStream << std::endl;
  72.     system("pause");
  73. }

16进制转码流

    抱歉!评论已关闭.