Converting from String to Hex, from Hex to Bytes, from Bytes to String using Google Apps script

Gists

This is a sample script for converting from the string value to the hex value, from the hex value to the byte array, from the byte array to the string value using Google Apps script.

When the creation of a signature for requesting and the encryption of data are used, there is the case that these conversions are required to be used. So I would like to introduce these scripts as sample scripts.

Sample script

const str = "sample string"; // This is a original string value.

// Convert string to hex.
const hexFromStr = Utilities.newBlob(str)
  .getBytes()
  .map((byte) => ("0" + (byte & 0xff).toString(16)).slice(-2))
  .join("");
console.log(hexFromStr); // <--- 73616d706c6520737472696e67

// Convert hex to bytes.
const bytesFromHex = hexFromStr
  .match(/.{2}/g)
  .map((e) =>
    parseInt(e[0], 16).toString(2).length == 4
      ? parseInt(e, 16) - 256
      : parseInt(e, 16)
  );
console.log(bytesFromHex); // <---  [ 115, 97, 109, 112, 108, 101, 32, 115, 116, 114, 105, 110, 103 ]

// Convert bytes to string.
const strFromBytes = Utilities.newBlob(bytesFromHex).getDataAsString();
console.log(strFromBytes); // <---  sample string
  • When this script is run,
    • At Convert string to hex, sample string is converted to 73616d706c6520737472696e67.
    • At Convert hex to bytes, 73616d706c6520737472696e67 is converted to [ 115, 97, 109, 112, 108, 101, 32, 115, 116, 114, 105, 110, 103 ].
      • At Google Apps Script, the bytes array is the signed hexadecimal. At Javascript, it’s the unsigned hexadecimal. I think that this is the important point.
    • At Convert bytes to string, [ 115, 97, 109, 112, 108, 101, 32, 115, 116, 114, 105, 110, 103 ] is converted to sample string.

 Share!