In this section, you'll learn about using the
Buffer object and the
Codec module to interact with binary data streams.
The Titanium.Codec provides utility methods to convert to and from binary data.
The Titanium.Stream module provides additional utility methods for working with streams.
Buffers are created from the Titanium module using
Titanium.createBuffer(). Buffers are similar to byte arrays in other programming languages but have the ability to be resized. Buffers may be grown by setting the
length property to a larger value, or when using the
append() methods. Their length may also be reduced by setting the
length property to a smaller value or using the
You can create an empty buffer with a specified initial size, or use a string or numeric value as the initial value of a buffer. The following code excerpt show several ways to initialize a buffer.
The following code excerpt shows some other manipulations on a buffer, including appending one buffer to another and truncating buffers.
Buffers can also be addressed directly as if they were arrays of byte values, as shown in the following code excerpt.
Also note that when assigning values to the buffer this way, the values must be byte values.
Codec module supports conversion of two basic primitive types: Numbers and Strings.
Codec also handles byte order conversion.
Codec module methods do not resize the target buffer.
Numeric conversion is provided for the following types:
The following code excerpt encodes a 4-byte integer into the buffer, starting at index 10 (the 11th byte of the integer).
The following code excerpt decodes the 4-byte integer written to the buffer in the previous example.
String conversion is provided using the following character sets:
UTF16LE. The default is UTF-8. Titanium.Codec also suports both Big Endian and Little Endian byte ordering.
The following excerpt encodes a string into a buffer, then trims the buffer to the length of the encoded string.
The following excerpt decodes a UTF-8 string from a buffer.
Buffer creation with encode
Titanium.createBuffer() has convenience options for creating a buffer from existing data. These options are just a convenient alternative to calling `createBuffer` and `encodeString` or `encodeNumber` separately, as shown in the following excerpt.