Skip to content

Core\Uuid::toBytes

$uuid->toBytes(): bytes

Returns the sixteen bytes of a Uuid. The bytes are in the same order as the digits of the UUID's text, so f9168c5e-… gives the bytes f9 16 8c 5e …. Use it to store a UUID in a binary database column, or to send it in a binary message. The text of the same UUID is 36 bytes long.

toBytes always works, and it always returns exactly sixteen bytes. Core\Uuid::fromBytes does the opposite: it reads the bytes back as the same Uuid.

The examples below print the bytes as hexadecimal, read them back to the same UUID, and write several UUIDs into one binary message.

Return value

Returns bytes. Sixteen bytes, in the same order as the digits of the UUID's text. Core\Uuid::fromBytes reads them back as the same UUID.

Examples

Show the sixteen bytes

<?nvs
// Shows the sixteen bytes of a UUID, written as hexadecimal.
var $id = Core\Uuid::parse('f9168c5e-ceb2-4faa-b6bf-329bf39fa1e4');
bytes $octets = $id->toBytes();
// This prints 16.
echo Core\Bytes::length($octets), "\n";
// The bytes are the digits of the text without the hyphens.
// This prints f9168c5eceb24faab6bf329bf39fa1e4.
echo Core\Encoding::toHex($octets), "\n";
Output
16
f9168c5eceb24faab6bf329bf39fa1e4

Read the bytes back

<?nvs
// Shows that `Core\Uuid::fromBytes` reads the bytes back as the same UUID.
var $id = Core\Uuid::v4();
bytes $octets = $id->toBytes();
var $again = Core\Uuid::fromBytes($octets);
// Both UUIDs have the same text. This prints "same".
echo $again->toString() == $id->toString() ? 'same' : 'different', "\n";
Output
same

Write ids into a binary message

<?nvs
// Shows how to write several UUIDs into one binary message, sixteen bytes each.
class Message
{
public static function of(array<Core\Uuid> $ids): bytes
{
array<bytes> $parts = [];
foreach ($ids as Core\Uuid $id) {
$parts[] = $id->toBytes();
}
return Core\Bytes::join($parts);
}
}
array<Core\Uuid> $ids = [
Core\Uuid::parse('0190d1e6-8e3c-7c2a-9a4b-1f2e3d4c5b6a'),
Core\Uuid::parse('f9168c5e-ceb2-4faa-b6bf-329bf39fa1e4'),
Core\Uuid::parse('00112233-4455-6677-8899-aabbccddeeff'),
];
bytes $message = Message::of($ids);
// Three UUIDs take 48 bytes. As text, they would take 108. This prints 48.
echo Core\Bytes::length($message), "\n";
// The second UUID starts at byte 16. This prints f9168c5e-ceb2-4faa-b6bf-329bf39fa1e4.
echo Core\Uuid::fromBytes(Core\Bytes::slice($message, 16, 16)), "\n";
Output
48
f9168c5e-ceb2-4faa-b6bf-329bf39fa1e4