View Full Version : Resolved ASCII -> Binary Conversion
keyboard
12-10-2013, 11:38 AM
Hey everybody!
Would anyone mind explaining how to convert ASCII bytes into their Binary form? (without using conversion tables)
The language doesn't actually matter, I'm just looking for the method of conversion.
I've tried googling it but haven't found anything overly helpful.
jscheuer1
12-10-2013, 03:04 PM
Do you mean just converting the hex and/or decimal designation of an ASCII character to a binary number?
Probably not, but if there's any correlation, I would think that would be the only way to do it without a table because on a computer, in the end everything is just a 1 or a 0.
For single characters, one at a time, in javascript that's:
function ascii2bin(c){
return c.charCodeAt(0).toString(2);
}
similarly, PHP has the ord (http://php.net/ord) function.
keyboard
12-11-2013, 03:34 AM
Sorry for the confusion: I do mean converting the ASCII value (E.g. G=71) to its binary counterpart.
I found this website (http://www.wikihow.com/Convert-from-Decimal-to-Binary) that shows how to do it manually. It should be translatable I guess.
--->
Here's how I did it.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function() {
$("#submit1").click(function() {
data = $("#input1").val();
num = 0;
iBuffer = "";
while(data > 0)
{
num = data % 2;
data = Math.floor(data / 2);
iBuffer += num;
}
iBuffer = iBuffer.split("").reverse().join("");
$("body").append('<br />' + iBuffer);
return false;
});
});
</script>
</head>
<body>
<textarea cols="10" rows="10" id="input1">71</textarea>
<input type="submit" value="Go" id="submit1"/>
</body>
</html>
<?php
$chr = 'a'; // a
$ord = ord( $chr ); // 97
$bin = decbin( $ord ); // 1100001
keyboard
12-11-2013, 05:54 AM
Yes, I did read that link you posted before traq. However I'd prefer to do the conversion without using an inbuilt function so it can be transferred across languages.
djr33
12-11-2013, 06:00 AM
Fair enough. But maybe this?
http://phpjs.org/
keyboard
12-11-2013, 06:23 AM
I don't mean just compatible between JS/PHP. I mean other languages as well. Anyways my question has been answered :)
djr33
12-11-2013, 07:18 AM
Well, one nice thing about phpjs is that it gives you the Javascript code for the PHP functions-- you can copy it to whatever you want :)
jscheuer1
12-11-2013, 02:28 PM
I see. Most if not all languages have number conversion routines. In your solution you use one of them (% - modulus), which converts a number to it's remainder when divided by another. It's really a matter of how much of the math you want to 'do yourself'.
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.