Created
June 18, 2014 05:11
-
-
Save ochinchina/a31eb36bcff2f41245da to your computer and use it in GitHub Desktop.
convert a binary string to HEX format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <iostream> | |
using std::string; | |
std::string hexPrint( const char* s, int n ) { | |
std::string result; | |
char buf[4]; | |
for( int i = 0; i < n; i+= 16 ) { | |
int m = ( n - i ); | |
if( m > 16 ) { | |
m = 16; | |
} | |
if( !result.empty() ) { | |
result += '\n'; | |
} | |
for( int j = 0; j < m; j++ ) { | |
sprintf( buf, "%02X ", ( s[i+j] & 0xff ) ); | |
result += buf; | |
} | |
for( int j = m; j < 16; j++ ) { | |
result += " "; | |
} | |
for( int j = 0; j < m; j++ ) { | |
if( ::isprint( s[i+j] ) ) { | |
result += s[i+j]; | |
} else { | |
result += '.'; | |
} | |
} | |
} | |
return result; | |
} | |
int main( int argc, char** argv ) { | |
char buf[256]; | |
for( int i = 0; i < 256; i++ ) { | |
buf[i] = (char)i; | |
} | |
std::cout << hexPrint( buf, 253 ) << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment