既然我喜欢这个,我想补充一些我刚刚写的东西,可能会有用。也许其他人也会发现它很有用。
Below's jsFiddle
原型:
Number.prototype.fromCharCode = function () {return String.fromCharCode(this); };
String.prototype.byte = function (val){ var a = new Array();
for(var i=(val||0),n=val===0?0:this.length-1; i<=n; i++){
a.push(this.charCodeAt(i) & 0xFF);
}
return a;
};
String.prototype.HiNibble = function (val){
var b = this.byte(val);
var a = new Array();
for(var i=0,n=b.length-1; i<=n; i++){a.push(b[i] >> 4);}
return a;
};
String.prototype.LoNibble = function (val){
var b = this.byte(val);
var a = new Array();
for(var i=0,n=b.length-1; i<=n; i++){a.push(b[i] & 0xF);}
return a;
};
呼叫示例:
var str = new String("aB");
console.log(str.byte()); // [ 97, 66 ]
console.log(str.HiNibble()); // [ 6, 4 ]
console.log(str.LoNibble()); // [ 1, 2 ]
console.log(str.byte(0)); // [ 97 ]
console.log(str.HiNibble(0)); // [ 6 ]
console.log(str.LoNibble(0)); // [ 1 ]
var bar = "c";
console.log(bar.byte()); // [ 99 ]
console.log(bar.HiNibble()); // [ 6 ]
console.log(bar.LoNibble()); // [ 3 ]
var foobar = (65).fromCharCode(); // from an integer (foobar=="A")
console.log(foobar.byte()); // [ 65 ]
console.log(foobar.HiNibble()); // [ 4 ]
console.log(foobar.LoNibble()); // [ 1 ]
/* Useful function that I modified
Originally from: http://www.navioo.com/javascript/dhtml/Ascii_to_Hex_and_Hex_to_Ascii_in_JavaScript_1158.html
*/
function AscHex(x,alg){
hex = "0123456789ABCDEF";
someAscii = ' !"#$%&\''
+ '()*+,-./0123456789:;=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\'
+ ']^_`abcdefghijklmnopqrstuvwxyz{|}';
r = "";
if(alg=="A2H"){
for(var i=0,n=x.length;i<n;i++){
let=x.charAt(i);
pos=someAscii.indexOf(let)+32;
h16=Math.floor(pos/16);
h1=pos%16;
r+=hex.charAt(h16)+hex.charAt(h1);
}
}
if(alg=="H2A"){
for(var i=0,n=x.length;i<n;i++){
let1=x.charAt(2*i);
let2=x.charAt(2*i+1);
val=hex.indexOf(let1)*16+hex.indexOf(let2);
r+=someAscii.charAt(val-32);
}
}
return r;
}
console.log(AscHex('65','A2H')); // A