javascript - 在Javascript中将字符串转换为字节字符串
问题描述
在 Python 中,我有以下代码将字节存储在变量中,例如:-
K = b"\x00" * 32
我试图编写此代码的 javascript 等效项以使用以下代码获取字节字符串:
function toUTF8Array(str) {
var utf8 = [];
for (var i = 0; i < str.length; i++) {
var charcode = str.charCodeAt(i);
if (charcode < 0x80) utf8.push(charcode);
else if (charcode < 0x800) {
utf8.push(0xc0 | (charcode >> 6), 0x80 | (charcode & 0x3f));
} else if (charcode < 0xd800 || charcode >= 0xe000) {
utf8.push(
0xe0 | (charcode >> 12),
0x80 | ((charcode >> 6) & 0x3f),
0x80 | (charcode & 0x3f)
);
}
// surrogate pair
else {
i++;
// UTF-16 encodes 0x10000-0x10FFFF by
// subtracting 0x10000 and splitting the
// 20 bits of 0x0-0xFFFFF into two halves
charcode =
0x10000 + (((charcode & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff));
utf8.push(
0xf0 | (charcode >> 18),
0x80 | ((charcode >> 12) & 0x3f),
0x80 | ((charcode >> 6) & 0x3f),
0x80 | (charcode & 0x3f)
);
}
}
return utf8;
}
但它正在生成字节数组,如下所示:
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0]
我不希望输出为纯数字数组。我需要像 Python 一样的字节输出(在 Python 代码中为:K = b"\x00" * 32)。如何做到这一点?
解决方案
推荐阅读
- typescript - 从嵌套参数中提取类型
- netsuite - Netsuite 已保存搜索检查相关记录中的字段
- django - Update view not displaying data
- python - 在 Python 中实现 peek() 方法时处理空堆栈的正确方法
- java - Can you "cast" a PCollection
to a PCollection to avoid deserialization? - java - If you have set spring.cloud.config.server.bootstrap=true, you need to use a composite configuration
- javascript - Typescript passing rest props to React component throws does not exist
- flutter - Scalling Image of a Carousel on Dragdown in Flutter
- flutter - Flutter:如何像 WhatsApp 一样在 Google Drive 上备份用户数据?
- c++ - Dynamic verb for Windows shell context/shortcut menu extension