Skip to main content
Version: 1.5.0

Strings & Bytes


Strings are defined using the built-in string type like this:

const a = "Hello Alice";

Concatenating Strings

Strings can be concatenated using the + operator.

const name = "Alice";
const greeting = "Hello";
const full_greeting = greeting + " " + name;

Extracting Substrings

Substrings can be extracted using the predefined function String.sub. The first character has index 0 and the interval of indices for the substring has inclusive bounds.

const name = "Alice";
const slice = String.sub (0n, 1n, name); // slice == "A"

⚠️ Notice that the offset and length of the slice are natural numbers.

Length of Strings

The length of a string can be found using a built-in function:

const name = "Alice";
const length = String.length(name); // length == 5


Byte literals are defined using the prefix 0x followed by hexadecimal digits like this:

const b = 0x7070;

Moreover, a string literal can be converted to its bytes representation:

const bs = (bytes `foo`);

Concatenating Bytes

Bytes can be concatenated using the Bytes.concat function.

const white = 0xffff;
const black = 0x0000;
const pixels = Bytes.concat(white, black); // 0xffff0000

Extracting Bytes

Bytes can be extracted using the predefined function Bytes.sub. The first parameter takes the start index and the second parameter takes the number of bytes. Pay special attention to how bytes are indexed.

const b = 0x12345678;
const slice = Bytes.sub (1n, 2n, b); // 0x3456

Length of Bytes

The length of bytes can be found using a built-in function Bytes.length:

const b = 0x123456;
const length = Bytes.length(b); // length = 3

Bitwise operators

You can perform bitwise operation on bytes as follows:

/* Bitwise and */
const b_and = 0x0005 & 0x0106; // 0x0004
/* Bitwise or */
const b_or = 0x0005 | 0x0106; // 0x0107
/* Bitwise xor */
const b_xor = 0x0005 ^ 0x0106; // 0x0103
/* Bitwise shift left */
const b_shift_left = 0x06 << 8n; // 0x0600
/* Bitwise shift right */
const b_shift_right = 0x0006 >> 1n; // 0x0003

From bytes to nat and back

You can case bytes to nat using the built-in nat function and vice-versa using using the bytes built-in function.

/* bytes -> nat */
const test_bytes_nat = nat(0x1234) // 1234n
/* nat -> bytes */
const test_nat_bytes = bytes(4660n) // 0x1234

From bytes to int and back

You can cast bytes to int using the built-in int function and vice-versa using the bytes built-in function.

/* bytes -> int */
const test_bytes_int = int(0x1234) // 4660
/* int -> bytes */
const test_int_bytes = bytes(4660) // 0x1234