我构建了一个简单的Web应用程序,该应用程序从端点接收一些代码并生成密钥,必须从中生成QR码。
结束键是一个Uint8Array
,需要将其制成QRCode,我正在使用angularx-qrcode
库,然后使用{{1将Uint8Array
转换为字符串}},但事实证明这种方法不适用于我的情况。
我需要从数组的原始HEX值生成QRCode,但是使用String.fromCharCode.apply(null, uintArray)
似乎会生成UTF-8字符,从而生成意外的字符。
到目前为止,我已经尝试使用一个库将字符串转换为名为String.fromCharCode
的'ISO-8859-1',但这似乎没有用。
我也尝试过像iconv-lite
这样的字符串进行转换,但是这引发了错误,说无效的URI,可能是因为结尾键包含的无效字符无法使用该功能。
以下是我的bytes数组的示例,其始终为20个字节长。
decodeURIComponent(escape(encodedString));
尽管给出了一些想法,但我认为问题可能也与QR代码库本身有关,所以我寻找了一个接收156,0,0,0,0,0,148,131,114,7,121,81,85,9,0,0,84,69,48,171
而不是字符串的QR代码库,但是我没有找到一个。
我的一位同事设法通过将字符串结尾为Uint8Array
而不是ISO-8859-1
来解决了android应用上的此问题。
我相信解决方案将是直接从bytes数组生成QRCode,这样我就无需打扰字符编码,但是如果有人知道其他方法可以解决此问题,我将很乐意尝试。
>我需要从这些字节生成的RAW字符串,例如第一个字节是UTF-8
,十六进制是156
,所以我需要代表9c的字符,但是9c
不是一个“常规” ASCII字符,这就是9c
对我不起作用的原因,就像该数组一样,结束字符串的长度应该至少为20个字节。
答案 0 :(得分:0)
据我了解,您无法从字节数组生成十六进制字符串? 试试这个功能:
function byteToHex(byte) {
// convert the possibly signed byte (-128 to 127) to an unsigned byte (0 to 255).
// if you know, that you only deal with unsigned bytes (Uint8Array), you can omit this line
const unsignedByte = byte & 0xff;
// If the number can be represented with only 4 bits (0-15),
// the hexadecimal representation of this number is only one char (0-9, a-f).
if (unsignedByte < 16) {
return '0' + unsignedByte.toString(16);
} else {
return unsignedByte.toString(16);
}
}
// bytes is a typed array (Int8Array or Uint8Array)
function toHexString(bytes) {
// Since the .map() method is not available for typed arrays,
// we will convert the typed array to an array using Array.from().
return Array.from(bytes)
.map(byte => byteToHex(byte))
.join('');
}
答案 1 :(得分:0)
我设法使用以下库解决了我的问题:QR-Code-generator
它允许从bytes数组以及常规字符串生成QRCode。
它非常轻巧且易于使用,并且支持许多不同的编程语言。 唯一的缺点是它不支持NPM,并且它的默认TypeScript实现有点差,它需要一些调整才能与我的项目一起使用,但是最终它运行良好,甚至支持SVG输出。