Javascript 将 Unicode 八进制字节转换为文本

Pro*_*orT 2 javascript unicode encoding character-encoding octal

我正在尝试使用 Javascript 将一系列八进制字节转换为文本,如下所示:

\n\n

输入是 \\330\\265 输出应该是 \xd8\xb5

\n\n

以下工具成功地做到了这一点:

\n\n\n\n

我正在尝试复制这个逻辑

\n

Mr.*_*irl 5

这是一个非常简单的任务,您所需要做的就是使用该Number.toString(radix)方法转换您从中返回的十进制整数值String.charCodeAt(index)以对字符串进行编码。

String.fromCharCode(charCode)使用和的组合parseInt(numberString, radix),您可以使用值 8 作为基数并将其传递给该fromCharCode方法来解码八进制值。

计划结果

Input:   Hello World
Encode:  110 145 154 154 157 040 127 157 162 154 144
Decode:  Hello World
Run Code Online (Sandbox Code Playgroud)

更新了代码

Input:   Hello World
Encode:  110 145 154 154 157 040 127 157 162 154 144
Decode:  Hello World
Run Code Online (Sandbox Code Playgroud)
const
  bytesToChars  = (bytes)    => bytes.map(byte => String.fromCharCode(parseInt(byte, 10))),
  charsToBytes  = (chars)    => chars.map(char => char.charCodeAt(0)),
  decToOctBytes = (decBytes) => decBytes.map(dec => dec.toString(8).padStart(3, '0')),
  octToDecBytes = (octBytes) => octBytes.map(oct => parseInt(oct, 8)),
  encode        = (str)      => decToOctBytes(charsToBytes(str.split(''))).join(' '),
  decode        = (octBytes) => bytesToChars(octToDecBytes(octBytes.split(/\s/))).join('');
  
let octBytes, str;
console.log('Input: ', str = 'Hello World');
console.log('Encode:', octBytes = encode(str));
console.log('Decode:', decode(octBytes));
Run Code Online (Sandbox Code Playgroud)

原始代码

.as-console-wrapper { top: 0; max-height: 100% !important; }
Run Code Online (Sandbox Code Playgroud)
/* Redirect console output to HTML. */ document.body.innerHTML = '';
console.log=function(){document.body.innerHTML+=[].slice.apply(arguments).join(' ')+'\n';};

var octBytes, str;
console.log('Input: ', str = "Hello World");
console.log('Encode:', octBytes = encode(str));
console.log('Decode:', decode(octBytes));

function encode(str) {
  return decToOctBytes(charsToBytes(str.split(''))).join(' ');
}

function decode(octBytes) {
  return bytesToChars(octToDecBytes(octBytes.split(' '))).join('');
}

function charsToBytes(chars) {
  return chars.map(function(char) {
    return char.charCodeAt(0);
  });
}

function bytesToChars(bytes) {
  return bytes.map(function(byte) {
    return String.fromCharCode(parseInt(byte, 10));
  });
}

function decToOctBytes(decBytes) {
  return decBytes.map(function(dec) {
    return ('000' + dec.toString(8)).substr(-3);
  });
}

function octToDecBytes(octBytes) {
  return octBytes.map(function(oct) {
    return parseInt(oct, 8);
  });
}
Run Code Online (Sandbox Code Playgroud)