Encode and decode Base64 data using WebAssembly WAT. Includes code in JavaScript for web browser and NodeJS.
This is an example of how to using the base64-web.js
JavaScript class to encode an array of bytes into a base64
encoded string, and to then decode back again.
import Base64Web from "./base64-web.js"; // Create base64 web object const base64 = new Base64Web(); // Load the instance await base64.load(); // Create array of data let arrayBuffer = new Uint8Array(3); arrayBuffer[0] = 0xB2; arrayBuffer[1] = 0x37; arrayBuffer[2] = 0xA5; // Encode into a base64 string let encoded = base64.encode(arrayBuffer); console.log(encoded); // Output: yeTp // Decode it back into an array let decoded = base64.decode(encoded); console.log(decoded); // Output: [0xB2, 0x37, 0xA5]
Each 3x bytes of data are encoded into 4x base64 characters. The table below shows the 3x bytes from right to left. The 3x bytes are seen as one long 24bit number. This is then split into 4x 6bit values. Each 6bit value number is converted into an ASCII character (see table below).
[0xB2, 0x37, 0xA5] => 'yeTp' HEX:| 0xA5 | 0x37 | 0xB2 | BIN:|1 0 1 0 0 1 0 1|0 0 1 1 0 1 1 1|1 0 1 1 0 0 1 0| :|1 0 1 0 0 1|0 1 0 0 1 1|0 1 1 1 1 0|1 1 0 0 1 0| :| 0x29 | 0x13 | 0x1E | 0x32 | B64:| p | T | e | y |
Each 6bit value has a range of values from 0
to 64
.
Each value is converted into a character, ranging from A
to Z
, a
to z
, 0
to 9
, +
and /
.
It also includes the special character =
for padding.
This library shows how to use WAT to perform the encoding and decoding of base64 data. It uses memory, string data and other parts to perform the operations in a quick and simple way.