Reputation: 10637
In Google AppsScript, I'm trying to Base64 encode a byte array using the Utilities
class.
UPDATE: Example of this here: https://script.google.com/d/15eLqgLHExpLG64JZhjUzKfBj4DgLhNZGBOkjwz7AkeeUbcgcaraP4y9X/edit?usp=sharing
// bytes to encode
var toenc = [ 0x52 , 0x49 , 0x46 , 0x46
, 0xBC , 0xAF , 0x01 , 0x00
, 0x57 , 0x41 , 0x56 , 0x45
, 0x66 , 0x6D , 0x74 , 0x20
, 0x10 , 0x00 , 0x00 , 0x00
, 0x01 , 0x00 , 0x01 , 0x00
, 0x40 , 0x1f , 0x00 , 0x00
, 0x40 , 0x1f , 0x00 , 0x00
, 0x01 , 0x00 , 0x08 , 0x00
, 0x64 , 0x61 , 0x74 , 0x61
, 0x98 , 0xaf , 0x01 , 0x00
];
// This errs with -- Cannot convert Array to (class)[]
Logger.log(Utilities.base64EncodeWebSafe(toenc));
// OK, typing issue? Following the doc, but still get same error :-(
Logger.log(Utilities.base64EncodeWebSafe(
Utilities.newBlob(toenc).getBytes()
));
Alas, the very same error Cannot convert Array to (class)[] on run.
If I have an array of (byte) numbers (effectively a string), am I able to employ the Utilities
class to Base64 it?
Upvotes: 1
Views: 1836
Reputation: 10637
Found the answer. It deals with the fact the function wants a 2's compliment number. Solution:
function to64(arr) {
var bytes = [];
for (var i = 0; i < arr.length; i++)
bytes.push(arr[i]<128?arr[i]:arr[i]-256);
return Utilities.base64EncodeWebSafe(bytes)
} // to64
https://stackoverflow.com/a/20639942/199305
Upvotes: 0
Reputation: 201388
Is a following script helpful for you? If I have misread your question, I apologize.
var toenc = [ 0x57 , 0x41 , 0x56 , 0x45
, 0x66 , 0x6D , 0x74 , 0x20
, 0x10 , 0x00 , 0x00 , 0x00
, 0x64 , 0x61 , 0x74 , 0x61
];
var a1 = Utilities.base64EncodeWebSafe(toenc);
var a2 = Utilities.base64DecodeWebSafe(a1, Utilities.Charset.UTF_8);
var a3 = Utilities.newBlob(a2).getDataAsString();
>>> a1 = V0FWRWZtdCAQAAAAZGF0YQ==
>>> a2 = [87, 65, 86, 69, 102, 109, 116, 32, 16, 0, 0, 0, 100, 97, 116, 97]
>>> a3 = WAVEfmt ���data
Upvotes: 1