954,593 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

JavaScript Binary/ASCII Converter

0
By itsjareds on Jun 16th, 2009 1:57 am

Here's a script I worked up to convert binary code into ASCII. Didn't work out an ASCII to binary conversion yet.

<html>
<head>

<script type="text/javascript">
var input_id = "bin_text";
var answer_id = "answer";

function convertToASCII() {
	var bin_text = document.getElementById(input_id);
	var answer = document.getElementById(answer_id);

	if (!answer) {
		alert("Error: No element with id \""+answer_id+"\".");
		return;
	}
	if (bin_text)
		var text = bin_text.value;
	else {
		error("No element with id \""+input_id+"\".");
		return;
	}
	var divisible = text.length % 8;
	var nonBinary = /[^0|1]/.test(text);
	if (text.length > 0 && divisible == 0 && !nonBinary) {
		var regex = /[0|1]{8}/g;
		var str = text.match(regex);
		var code = 0;
		var placeVal, exp, digit;
		var ascii = '';
		while (str.length > 0) {
			code = 0;
			for (var i=0; i<str[0].length; i++) {
				placeVal = 7-i;
				exp = Math.pow(2, i);
				digit = str[0].charAt(placeVal);
				code += exp*digit;
			}
			str.shift();
			ascii += String.fromCharCode(code);
		}
		answer.innerHTML = "<p class=\"binary\">" + ascii + "</p>";
	}
	else {
		error("Malformed binary.");
		return;
	}

	function error(errText) {
		answer.innerHTML = "<span class=\"error\">Error: " + errText + "</span>";
	}
}
</script>

<style type="text/css">
.block {
	width: 45%;
	border: 1px solid #000000;
	padding: 10px;
}
.binary {
	background-color: #C6FFC7;
	padding: 3px;
}
.error {
	background-color: #FFC6C6;
	padding: 3px;
}
</style>

</head>
<body>

<div style="float:left;" class="block">
	<form onSubmit="convertToASCII(); return false;">
		<p>Enter some binary to decode:</p>

		<input type="text" id="bin_text"/>
	</form>
</div>

<div style="float:right;" class="block">
	<p id="answer"><br/></p>
</div>

</body>
</html>

Something not really used in JS is the second parameter of parseInt().

You can use it to convert between bases:

eg:

// binary to decimal
parseInt('101', 2); // 5


So converting between binary and ASCII would be as simple as:

// binary to unicode character
function bin2ascii(bin) {
  return String.fromCharCode(parseInt(bin, 2));
}


source: http://www.bucabay.com/web-development/base-conversion-in-javascript/

digital-ether
Nearly a Posting Virtuoso
Moderator
1,293 posts since Sep 2005
Reputation Points: 461
Solved Threads: 101
 

Oooh, I didn't know of that. Oh well, it was interesting to give a shot at it myself.

itsjareds
Junior Poster
103 posts since May 2009
Reputation Points: 39
Solved Threads: 13
 

It is a good exercise.

digital-ether
Nearly a Posting Virtuoso
Moderator
1,293 posts since Sep 2005
Reputation Points: 461
Solved Threads: 101
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You