如何转换UINT8数组为Base64恩codeD字符串? [英] How to convert uint8 Array to base64 Encoded String?
问题描述
我得到了一个WebSocket的交际,我收到的base64 EN codeD字符串,将其转换为UINT8和工作就可以了,但现在我需要送回去,我得到了UINT8数组,需要将其转换为Base64字符串,这样我就可以把它。
我怎样才能让这个皈依?
I got a webSocket comunication, I recieve base64 encoded string, convert it to uint8 and work on it, but now I need to send back, I got the uint8 array, and need to convert it to base64 string, so I can send it. How can I make this convertion?
推荐答案
为Base64 EN code一Uint8Array:
To base64 encode a Uint8Array:
var u8 = new Uint8Array([65, 66, 67, 68]);
var b64encoded = btoa(String.fromCharCode.apply(null, u8));
和脱code中的字符串的base64回到一个Uint8Array:
And to decode the base64 string back to a Uint8Array:
var u8_2 = new Uint8Array(atob(b64encoded).split("").map(function(c) {
return c.charCodeAt(0); }));
更新
的Mozilla最近发布的包含在类型化数组一个 StringView 处理字符串。具体请查看bytesToBase64方法可能是你想要的。
Mozilla recently released a StringView for manipulating strings contained in Typed Arrays. Specifically the bytesToBase64 method is probably what you want.
如果这是太重的重量,那么这里是一个简单的程序(基于一个张贴@RohitSengar),一个Uint8Array转换为字符串(然后可以很容易地采用base64 EN codeD):
If that's too heavy weight, then here is a simple routine (based on the one posted by @RohitSengar) that converts a Uint8Array to a string (which can then be easily base64 encoded):
function Uint8ToString(u8a){
var CHUNK_SZ = 0x8000;
var c = [];
for (var i=0; i < u8a.length; i+=CHUNK_SZ) {
c.push(String.fromCharCode.apply(null, u8a.subarray(i, i+CHUNK_SZ)));
}
return c.join("");
}
// Usage
var u8 = new Uint8Array([65, 66, 67, 68]);
var b64encoded = btoa(Uint8ToString(u8));
这篇关于如何转换UINT8数组为Base64恩codeD字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!