A Place For Answers

String Base Conversion – for Node.js & JavaScript

This goes out to all you Node.js and JavaScript people out there.
From normal to binary base, we’ll have to turn each string to unicode and then make it binary:

function encode (plainString ) {
	var encodedArray = [];
	for (var i = 0; i < plainString.length; i++) {
		encodedArray.push(plainString.charCodeAt(i).toString(2));
	};
	return encodedArray.join().replace(/,/g,'');
}

Just remember the function does not pad the string with zeros, so for instance “0” will become “110000” and not “00110000”.
Getting back to normal from binary is a bit easier:

function (encodedString) {
	var plainString  = "";
	for (var i = 0; i < encodedString.length; i+=8) {
		var c = String.fromCharCode(parseInt(encodedString.substr(i,8),2));
		plainString = plainString + c;
	};
	return plainString;
}

This bit of code will take every 8 characters,turn it to unicode and then change it to normal characters in normal base.

As always, stay tuned.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s