# Fastest number to/from binary string functions?

The following functions are great for saving Bandwidth when sending data over wires,
wondering if anyone has a way to speed them up at all? As they get used a lot when needed.

Usage examples:

``````
\$str=ConvertToBin(2,12323);  //packs the value 12323 into 2 byte string
\$num=ConvertFromBin(\$str);   // \$num becomes 12323 again.

``````

My functions:

``````
public static function ConvertToBin(bytes:uint,val:uint):String { //Convert to a 1-5 byte bin string
if (bytes==1) return String.fromCharCode(val&255);
if (bytes==2) return String.fromCharCode(val>>8&255,val&255);
if (bytes==3) return String.fromCharCode(val>>16&255,val>>8&255,val&255);
if (bytes==4) return String.fromCharCode(val>>24&255,val>>16&255,val>>8&255,val&255);
trace("Error Exceeded 4 bytes bin!");
}

public static function ConvertFromBin(str:String):Number { //return the decimal from bin string
var i:Number=str.length;
var val:Number=0;
if (i==0) return val;
val=str.charCodeAt(i-1);
if (i==1) return val;
val+=(str.charCodeAt(i-2)<<8);
if (i==2) return val;
val+=(str.charCodeAt(i-3)<<16);
if (i==3) return val;
val+=(str.charCodeAt(i-4)<<24);
if (i==4) return val;
val+=(str.charCodeAt(i-5)<<32);
if (i==5) return val;
trace("ConvertingFromBin on too long a string:"+i);
return val;
}

``````

Thanks!