Skip to content

Instantly share code, notes, and snippets.

@ochinchina
Created June 18, 2014 05:11
Show Gist options
  • Save ochinchina/a31eb36bcff2f41245da to your computer and use it in GitHub Desktop.
Save ochinchina/a31eb36bcff2f41245da to your computer and use it in GitHub Desktop.
convert a binary string to HEX format
#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