I have an Array (of numbers) in Google Apps Script, and I want to convert it to base64. I could of course use a simple open-source library such as this one.
However GAS already provides functions for this using Utilities.base64Encode(Byte[])
but to call this function I need a Byte[]
not Number[]
.
Therefore the following script gives an error: (Cannot convert Array to (class)[].
)
function testBase64Encode()
{
var bytes = [];
for (var i = 0; i < 255; i++) bytes.push(i);
var x = Utilities.base64Encode(bytes)
}
Normally Byte[]
's come directly out of a Blob's GetBytes()
function, however in my case the Array (of numbers) comes out of zlib encryption lib.
So I am trying to find a way to convert that Number Array to a Byte[]
, acceptable for use with Utilities.base64Encode(Byte[])
.
I did try to create a Byte myself and put them into an Array, however the following code also gives an error: (ReferenceError: "Byte" is not defined.
)
var b1 = new Byte();
I did some more testing, and it seems to work as long as the value in the bytes' numeric values are 128 or lower. I find this weird because a byte should go up to 255.
The following code runs fine for 'bytes' but fails for 'bytes2' because there is a value greater than 128:
function testByteArrays()
{
var bytes = [];
for (var i = 0; i < 128; i++) bytes.push(i);
var x = Utilities.newBlob(bytes)
var bytes2 = [];
for (var i = 0; i < 129; i++) bytes2.push(i);
var x = Utilities.newBlob(bytes2)
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…