关于纯数字的字符串按ASCII压缩
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> New Document </TITLE> <META NAME="Generator" CONTENT="EditPlus"> <META NAME="Author" CONTENT=""> <META NAME="Keywords" CONTENT=""> <META NAME="Description" CONTENT=""> <SCRIPT LANGUAGE="JavaScript"> //压缩前字符串 var _former = "23475439057468947233475094759027569027589720954764597063576037856975607458673087620720457634895768495764895638963470634706945769485762"; //var _former = "2330248"; /** * 压缩算法,分别取出两个数字转换成ASCII码,如果字符个数为奇数时,返回最后一位的负数值 * @param _former : 准备压缩的字符串 * @return _arr : 压缩后的数组 * @auth 方小洲 */ function _doZip(_former){ //定义数组、数组长度 var _arr = [] ; var _len = 0 ; //循环取出两个数字 for(var i = 0 ; i < _former.length - 1 ; i=i+2){ var _tmp = String.fromCharCode(_former.substring(i,i+2)); _arr[_len++] = _tmp ; } //如果字符个数为奇数时,返回最后一位的负数值 if(_former.length % 2 == 1){ _arr[_len++] = "-"+_former.charAt(_former.length-1); } return _arr ; } /** * 压缩算法,分别取出两个数字转换成ASCII码,如果字符个数为奇数时,返回最后一位的负数值 * @param _arr : 准备解压的数组 * @return _latter : 解压后的字符串 * @auth 方小洲 */ function _doUnZip(_arr){ //定义数组、数组长度 var _brr = [] ; var _len = 0 ; //循环取出每个字符,把ASCII转换成数字 for(var i = 0 ; i < _arr.length -1 ; i++){ var _tmp = _arr[i].charCodeAt(0); if(parseInt(_tmp) < 10 ){ _tmp = "0" + _tmp ; } _brr[_len++] = _tmp ; } //取出数组的最后一个元素 var _theLast = _arr[_arr.length - 1]; //如果长度大于1,表示为负数,返回其绝对值就可以了 if(_theLast.length > 1) { var _tmp = parseInt(_theLast); _tmp = Math.abs(_tmp); _brr[_len++] = _tmp ; }else { //表示正常压缩,按原来的解压 var _tmp = _theLast.charCodeAt(0); if(parseInt(_tmp) < 10 ){ _tmp = "0" + _tmp ; } _brr[_len++] = _tmp ; } //把数组转换为字符串 var _latter = _brr.join(''); return _latter ; } /** * 把数组变成字符串 * @param _arr : 数组 * @return _str : 返回的字符串 * @auth 方小洲 */ function _changeArrayToString(_arr){ var _str = _arr.join(''); return _str ; } var _latter = _doZip(_former); document.write("压缩前:"+_former + "<br/>" ); document.write("压缩后:"+_changeArrayToString(_latter) + "<br/>" ); document.write("解压后:"+_doUnZip(_latter) + "<br/>" ); </SCRIPT> </HEAD> <BODY> </BODY> </HTML>只支持纯数字
相关推荐
DCXabc 2020-05-05
bnmcvzx 2020-05-03
fengjing81 2020-02-19
dxbjfu0 2020-01-24
zhglinux 2019-12-11
typhoonpython 2019-11-19
playis 2019-11-09
风火一回一生不毁 2014-05-29
独行者0 2019-10-31
88941536 2019-08-02
shlamp 2013-01-04
ScarlettYellow 2015-05-05
一只懒虫 2019-06-29
yangkunlun 2019-06-28
jaminliu0 2019-06-28
kevinweijc 2013-06-04
church 2019-06-21