I'm working with UUIDs in PHP and I have to query a database that stores the most significant bits and least significant bits of a UUID in two separate columns. I found this question for Python, which seems like exactly what I'd need in PHP, but I don't know how to convert the code, and I've never been great with byte manipulation.
What would the equivalent functions for getLeastSignificantBits()
and getMostSignificantBits()
be in PHP? Thanks!
Edit: Example data (if helpful):
UUID: b33ac8a9-ae45-4120-bb6e-7537e271808e
...should convert to...
Upper Bits: -5531888561172430560
Lower Bits: -4940882858296115058
You simply need two libraries and bcmath extension, using
composer require ramsey/uuid moontoast/math
.
Parse UUID using Ramsey\Uuid\Uuid
:
$uuid = \Ramsey\Uuid\Uuid::fromString('b33ac8a9-ae45-4120-bb6e-7537e271808e');
echo 'Upper Bits: ' . $uuid->getMostSignificantBits() . "\n";
echo 'Lower Bits: ' . $uuid->getLeastSignificantBits() . "\n";
You get:
Upper Bits: 12914855512537121056
Lower Bits: 13505861215413436558
Using those methods you get Moontoast\Math\BigNumber
object, so you can get it's value or convert to different bases:
$higher = $uuid->getMostSignificantBits();
echo 'Upper Bits 10-base: ' . $higher->getValue() . "\n";
echo 'Upper Bits hex: ' . $higher->convertToBase(16) . "\n";
You get:
Upper Bits 10-base: 12914855512537121056
Upper Bits hex: b33ac8a9ae454120
You can also use $uuid->getMostSignificantBitsHex()
and $uuid->getLeastSignificantBitsHex()
which are already converted to hex.