C++ Programming Example

Convert to Binary

Converts a character or string into a binary string (a string of "0" or "1";s). The use of std::string removes any need for dynamic allocation and pointer maintenance. From:
http://www.experts-exchange.com/Programming/Programming_Languages/Cplusplus/Q_20525179.html

#include <string>
using namespace std;

string Byte2Binary(unsigned char c) {
string S;
unsigned char Msk = 0x80;

	for (int i = 0; i < 8; ++i) {
		if (c & Msk) S += '1';
		else S += '0';
		Msk >>= 1;
		}
	return S;
	}

string String2Binary(const string &S) {
const int StrLen = S.length();
string Result;

	for (int i = 0; i < StrLen; ++i)
		Result  += Byte2Binary(unsigned char) S[i]);
	return Result;
	}