C++: Outputting a string as hexadecimal characters…

… is easy with the boost format library:

Digging the net for examples was not very productive, so I started my own approach:

The trick is the “%x” which will output the numerical value (uint)s[i] as hexadecimal value.

If you have to deal with non printable characters, you might want to leave out the “<< s[i]” part, as it might mess up your screen output.

#include <boost/format.hpp>
string s="luan78zao";
cout<<"Length: "<<s.length()<<endl;

for (uint i=0; i<s.length(); i++)
   cout<< i << " " << s[i] <<" "<< boost::format ("%x") % (uint)s[i] <<endl;  



This entry was posted in code snippets, Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s