javascript , json字符串转hex , base64toHEX , hexToBase64 ,arrayBufferToBase64, hextoString
// hex转json字符串,16进制ASCII
var hextoString = function (hex) {
var arr = hex.split("")
var out = ""
for (var i = 0; i < arr.length / 2; i++) {
var tmp = "0x" + arr[i * 2] + arr[i * 2 + 1]
var charValue = String.fromCharCode(tmp);
out += charValue
}
return out
};
// json字符串转hex
var stringtoHex = function (str) {
var val = "";
for (var i = 0; i < str.length; i++) {
if (val == "")
val = str.charCodeAt(i).toString(16);
else
val += str.charCodeAt(i).toString(16);
}
val += "0a"
return val
//64 转hex
function base64toHEX(base64) {
var raw = atob(base64);
var HEX = '';
for ( i = 0; i < raw.length; i++ ) {
var _hex = raw.charCodeAt(i).toString(16)
HEX += (_hex.length==2?_hex:'0'+_hex);
}
return HEX.toUpperCase();
}
console.log(base64toHEX("oAAABTUAAg=="));
}
function hexToBase64(str) {
return btoa(String.fromCharCode.apply(null,
str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" "))
);
}
function base64ToHex(str) {
for (var i = 0, bin = atob(str.replace(/[ \r\n]+$/, "")), hex = []; i < bin.length; ++i) {
var tmp = bin.charCodeAt(i).toString(16);
if (tmp.length === 1) tmp = "0" + tmp;
hex[hex.length] = tmp;
}
return hex.join(" ");
}
arrayBufferToBase64( buffer ) {
var binary = '';
var bytes = new Uint8Array( buffer );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa( binary );
}
...常用后续补充
|