Skip to content

Instantly share code, notes, and snippets.

@moluapple
Created May 1, 2012 13:33
Show Gist options
  • Save moluapple/2567924 to your computer and use it in GitHub Desktop.
Save moluapple/2567924 to your computer and use it in GitHub Desktop.
字符及其 Hex 值互换
function hex2Ascii (str) {
return str.replace(/../g, function (a) {return String.fromCharCode('0x' + a)})
}
function ascii2Hex (hex) {
return hex.replace(/./g, function (a) {return a.charCodeAt(0).toString(16)})
}
function GBK2Hex (str/*中文字符*/) {
var f = File('hex.txt'), hex;
f.encoding = 'UTF8';
f.open('w'), f.write(str), f.close();
f.encoding = 'BINARY';
f.open('r');
hex = f.read().toSource().replace(/(?:\(new String\("|"\)\)|\\u00)/g, '');
f.close(), f.remove();
return hex
}
function hex2GBK (hex) {
var f = File('gbk.txt'),
GBK = eval('(new String("' + hex.replace(/../g, function (a) {return '\\u00' + a}) + '"))');
f.encoding = 'BINARY';
f.open('w'), f.write(GBK), f.close();
f.encoding = 'UTF8';
f.open('r');
GBK = f.read();
f.close(), f.remove();
return GBK
}
ascii2hex('animalia'); // 616e696d616c6961
hex2Ascii('616e696d616c6961'); // animalia
GBK2Hex('跳入苹果'); // E8B7B3E585A5E88BB9E69E9C
hex2GBK('E8B7B3E585A5E88BB9E69E9C'); // 跳入苹果
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment