Skip to content

Core\Bytes::at

Returns one byte of a bytes value as a number from 0 to 255.

The position counts from the start, so 0 is the first byte. A negative position counts from the end, so -1 is the last byte. If the position names a byte that is not there, this throws an error. Catch Throwable around it when the position comes from outside your program.

The value may be tainted bytes, and the result is still a plain number.

Good to know: the result is a number, not a bytes value of one byte. A number is what you need to compare a byte with a known value, such as the 0x89 that every PNG file starts with.

Parameters

  • $bbytesThe buffer.
  • $indexintThe position of the byte. A negative index counts from the end.

Return value

Returns uint. The byte as a number from 0 to 255.

Errors

  • RuntimeError$index is outside $b.

Changelog

VersionChange
0.0.6Core\Bytes::at takes tainted bytes and returns a plain uint. Core\Bytes::join takes an array<tainted bytes>, and the result is then tainted bytes.

Examples

Reading bytes by position

<?nvs
// Shows how to read single bytes out of a `bytes` value. Each byte comes back
// as a number from 0 to 255.
// There is no way to write bytes directly in a program, so this converts text.
bytes $data = 'Hi!' as bytes;
// Position 0 is the first byte. This prints 72, 105 and 33.
echo Core\Bytes::at($data, 0), "\n";
echo Core\Bytes::at($data, 1), "\n";
echo Core\Bytes::at($data, 2), "\n";
Output
72
105
33

Counting from the end

<?nvs
// Shows how to read the last byte of a `bytes` value, and what happens when
// the position is outside it.
bytes $data = 'abc' as bytes;
// A negative position counts from the end. -1 is the last byte, so this
// prints 99, the number for "c".
echo Core\Bytes::at($data, -1), "\n";
// -3 is the first byte, so this prints 97.
echo Core\Bytes::at($data, -3), "\n";
// Position 3 is outside a value of 3 bytes. `Core\Bytes::at` throws an error,
// and this prints the message.
try {
echo Core\Bytes::at($data, 3), "\n";
} catch (Throwable $e) {
echo $e->message, "\n";
}
Output
99
97
Core\Bytes::at: index 3 is outside a buffer of 3 bytes

Recognising an uploaded file

<?nvs
// Shows how a program works out what kind of file somebody uploaded. Every PNG
// file starts with the same eight bytes, so reading those bytes is enough.
class Upload
{
// Returns true when the uploaded bytes start with the eight bytes of a PNG
// file.
public static function isPng(bytes $file): bool
{
array<uint> $signature = [137, 80, 78, 71, 13, 10, 26, 10];
if (Core\Bytes::length($file) < 8) {
return false;
}
int $i = 0;
while ($i < 8) {
if (Core\Bytes::at($file, $i) != $signature[$i]) {
return false;
}
$i = $i + 1;
}
return true;
}
}
bytes $png = Core\Encoding::fromHex('89504e470d0a1a0a49484452');
bytes $letter = 'Dear customer,' as bytes;
// This prints "yes" and then "no".
echo Upload::isPng($png) ? 'yes' : 'no', "\n";
echo Upload::isPng($letter) ? 'yes' : 'no', "\n";
Output
yes
no