Skip to content

Bytes

Built-in type · Made with Bytes.from_list([72, 105]), “Hi”.to_bytes(), or File.read_binary(path)

Bytes holds binary data exactly as stored: the contents of an image, a sound, or any file that is not text. Each byte is a whole number from 0 to 255. A String must always be valid text, so data that may not be text belongs in Bytes. Like a String, Bytes never changes; its methods give back new values.

const data = Bytes.from_list([72, 105, 0, 255])
print(data) # prints Bytes[4: 48 69 00 ff]
print(data[0]) # prints 72

Bytes prints its bytes in hexadecimal, never as raw characters, so printing binary data can never garble the terminal.

Making and converting
Bytes.from_list(numbers) Bytes from whole numbers
to_string(), to_string_maybe() The bytes read as text
to_hex() The bytes written as hexadecimal digits
Bytes.from_hex(text), Bytes.from_hex_maybe(text) Bytes read from hexadecimal digits
Reading
count How many bytes
Operator Meaning Example
bytes[index] One byte, as an Int data[0] → 72
bytes[start..<end] Some of the bytes data[1..<3] → Bytes[2: 69 00]
+ Join two a + b
== != Compare byte by byte

To turn text into bytes, use String’s to_bytes(), which gives its UTF-8 encoding. To read and write files of bytes, use File.read_binary and File.write_binary.

Bytes.from_list(numbers: List[Int]): Bytes

Bytes made from a list of whole numbers, each from 0 to 255.

Bytes.from_list([72, 105]) # → Bytes[2: 48 69]

Raises a RuntimeError when a number is not from 0 to 255.

to_string(): String

The bytes read as UTF-8 text.

"Hi".to_bytes().to_string() # → "Hi"

Raises an EncodingError when the bytes are not valid UTF-8 text.

to_string_maybe(): String?

The bytes read as UTF-8 text, or nothing when they are not valid text.

Bytes.from_list([255]).to_string_maybe() # → nothing

to_hex(): String

The bytes written as hexadecimal, two lowercase digits for each byte. It is the usual way to show a checksum, such as the result of Digest.sha256.

print(Bytes.from_list([72, 105, 0, 255]).to_hex())
Output
486900ff

Bytes.from_hex(text: String): Bytes

Bytes read from hexadecimal digits, two for each byte, in upper or lower case. It is the opposite of to_hex.

print(Bytes.from_hex("48690fFF"))
Output
Bytes[4: 48 69 0f ff]

Raises an EncodingError when there is an odd number of digits, or a character that isn’t a hexadecimal digit.

Bytes.from_hex_maybe(text: String): Bytes?

Like from_hex, but gives nothing instead of raising an error.

print(Bytes.from_hex_maybe("abc"))
print(Bytes.from_hex_maybe("4869"))
Output
nothing
Bytes[2: 48 69]

count: Int

How many bytes there are.

Bytes.from_list([72, 105]).count # → 2