A Place For Answers

Posts tagged “string

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++) {
	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.