gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:52:50 25 4
gpt4 key购买 nike

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

输入是\330\265 输出应该是 õ

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

我正在尝试复制这个逻辑

最佳答案

这是一个非常简单的任务,您需要做的就是使用 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

更新代码

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));
.as-console-wrapper { top: 0; max-height: 100% !important; }

原始代码

/* 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);
});
}
body { font-family: monospace; white-space: pre; }

关于Javascript 将 Unicode 八进制字节转换为文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30236912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com