Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

javascript - How to load an Array (of numbers) into a google app script Byte[]

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

...a byte should go up to 255.

But not in Two's complement notation... in that case, the bytes should be in the range [-128..127], where the high-order bit is reserved as a sign bit. Given a positive integer i, we need to calculate the two's complement if it is greater than 127. That can be done by subtracting 28 (256). Applying that to your first example:

function testBase64Encode()
{
  var bytes = [];
  for (var i = 0; i < 255; i++) bytes.push(i<128?i:i-256);

  var x = Utilities.base64Encode(bytes)
} 

This will avoid the error message you were receiving (Cannot convert Array to (class)[].). Ideally, you should also ensure that the number values start in the range 0..255.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...