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

Gists

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

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

 Share!