Tuesday, May 15, 2007

Bangla to Hex

Here is my Bangla to Hex converter using php and little ajax. Thanks to Mr. Jamil for giving me this idea.



index.php

<html>
<head>
<script type="text/javascript" src="ajax.js"> </script>
</head>
<body>
<div align="center"><h1>Bangla HEX</h1></div>
<div align="center">salahuddin66.blogspot.com</div>
<br><br>
<form>
Input in UTF-8: <input type="text" name="input" onkeyup="show(this.value)">
</form>
<p>Hex: <span id="txtHint"></span></p>
</body>
</html>

ajax.js

var xmlHttp

function show(str0)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="show.php"
url=url+"?q="+str0
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}


show.php
<?php

$q=$_GET["q"];

unibin2hex($q);

function unibin2hex($u) {
$k = mb_convert_encoding($u, 'UCS-2LE', 'UTF-8');

$position = 0;

$run = strlen($u)/3;

for($i=0; $i<$run; $i++) //bengali char strlen return 3 for one char so div by 3 . Here run the loop for i
{

$k1 = bin2hex(substr($k, $position, 1)); //convert unicode part by part using bin2hex using substr
$k2 = bin2hex(substr($k, $position+1, 1));

$out = $k2.$k1; //combine two sub scring that we use to convert.

echo " ". $out; // out

$position = $position +2; //here we are converting part by part by so we need to increase 2 in every step

}
}
?>

1 comment:

Shehab said...

I love Ajax. Although I do it with Java.