Skip to content

SpecificationIII · Types and values

3.14

Bytes

Bytes is a sequence of octets, numbers from 0 to 255; it is used to work with binary data, such as the exact content of a file.

Markdown version

3.14.1 How to write it

Define «name» As Bytes <- Bytes();
Define «name» As Bytes <- bytesFromText(«text»);
«name».at(«position»)
«name».segment(«start», «count»)

3.14.2 How it works

A text is a row of characters; bytes are the way that text is stored in a file or travels over the network. Converting a text to bytes uses the UTF-8 encoding. Letters without accents take one octet, but ñ takes two.

ProgramThe octets of a word

Algorithm Octetos
  Define datos As Bytes <- bytesFromText("año");
  Write datos.length(), " ", datos.at(0), " ", datos.at(1), " ", datos.at(2);
  Define vacio As Bytes <- Bytes();
  Write vacio.length();
EndAlgorithm

Output

4 97 195 177
0

The program finishes normally.

Figure 3.14-1."año" has three characters but four octets: ñ is encoded with two.

At the top, the three characters of año: a, ñ and o. Below, their four octets: 97 for a, 195 and 177 for ñ, and 111 for o.

Decoding goes the other way and returns a Result, because not every byte sequence is a valid text:

ProgramFrom bytes to text

Algorithm Decodificar
  Define datos As Bytes <- bytesFromText("año");
  Switch datos.utf8Text() Do
    Success(texto): Write texto, " (", length(texto), " caracteres)";
    Otherwise: Write "no es UTF-8";
  EndSwitch
EndAlgorithm

Output

año (3 caracteres)

The program finishes normally.

In short

  • Bytes is an immutable sequence of octets from 0 to 255.
  • Text is encoded to UTF-8; decoding returns a Result.
  • Some characters take several octets.