Convert Hex String to Hex Value

前端 未结 4 1038
别那么骄傲
别那么骄傲 2020-12-21 11:30

I have a large hex string

abcdef...

and I want to convert it to

0xab 0xcd 0xef 

Are there any functions

4条回答
  •  情深已故
    2020-12-21 12:18

    You can do this using string streams.

    #include 
    #include 
    #include 
    
    int main( int , char ** )
    {
      const char *str = "AFAB2591CFB70E77C7C417D8C389507A5";
      const char *p1  = str;
      const char *p2  = p1;
    
      std::vector output;
    
      while( *p2 != NULL ) {
        unsigned short byte;
    
        ++p2;
        if( *p2 != NULL ) {
          ++p2;
        }
    
        std::stringstream sstm( std::string( p1, p2 ) );
    
        sstm.flags( std::ios_base::hex );
        sstm >> byte;
    
        output.push_back( byte );
    
        p1 += 2;
      }
    
      for( std::vector::const_iterator it = output.begin(); it != output.end(); ++it ) {
        std::cout << std::hex << std::showbase << *it << "\t" << std::dec << std::noshowbase << *it << "\n";
      }
    
      std::cout << "Press any key to continue ...";
      std::cin.get();
    }
    

    Note that if you use unsigned char instead of unsigned short the conversion from stringstream attempts to convert it into an ASCII character and it doesn't work.

提交回复
热议问题