Z
zirzofer
Guest
zwei funktionen, um einen string zu einem uint8array zu konvertieren bzw. umgekehrt:
Funktioniert soweit auch. Bloss nicht, wenn der String eine Zahl enthält:
was ist falsch, wie mache ich es richtig?
Code:
var strToUint8 = function (string) {
let encodedString, uint8Array;
encodedString = encodeURIComponent(string).replace(/%([0-9A-F]{2})/g, function (match, p1) {
return String.fromCharCode("0x" + p1);
});
uint8Array = new Uint8Array(encodedString.length);
Array.prototype.forEach.call(encodedString, function (c, i) {
uint8Array[i] = c.charCodeAt(0);
});
return uint8Array;
};
var uint8ToStr = function (uint8Array) {
let string, encodedString;
string = Array.prototype.map.call(uint8Array, function (c) {
return String.fromCharCode(c);
}).join("");
encodedString = string.replace(/(.)/g, function (m, p) {
let code;
code = p.charCodeAt(p).toString(16).toUpperCase();
if (code.length < 2) {
code = "0" + code;
}
return "%" + code;
});
return decodeURIComponent(encodedString);
};
var a = strToUint8("demo #!");
console.info(uint8ToStr(a));
var b = strToUint8("demo 123");
console.info(uint8ToStr(b));
URIError: malformed URI sequence
was ist falsch, wie mache ich es richtig?