【问题标题】:PHP equivalent of getLeastSignificantBits() & getMostSignificantBits from Java?PHP 相当于来自 Java 的 getLeastSignificantBits() 和 getMostSignificantBits?
【发布时间】:2018-05-07 22:51:47
【问题描述】:

我正在使用 PHP 中的 UUID,我必须查询一个数据库,该数据库将 UUID 的最高有效位和最低有效位存储在两个单独的列中。我找到了this question for Python,这似乎正是我在 PHP 中所需要的,但我不知道如何转换代码,而且我对字节操作从来都不是很好。

在 PHP 中 getLeastSignificantBits()getMostSignificantBits() 的等效函数是什么?谢谢!

编辑:示例数据(如果有帮助):

UUID: b33ac8a9-ae45-4120-bb6e-7537e271808e

...应该转换为...

Upper Bits: -5531888561172430560
Lower Bits: -4940882858296115058

【问题讨论】:

  • 我认为你可以自己实现它。为什么不呢?
  • @user202729 我在问题中解释了为什么我很难编写实现。

标签: java php uuid guid


【解决方案1】:

你只需要两个库和 bcmath 扩展, 使用

composer require ramsey/uuid moontoast/math.

使用Ramsey\Uuid\Uuid解析UUID:

$uuid = \Ramsey\Uuid\Uuid::fromString('b33ac8a9-ae45-4120-bb6e-7537e271808e');
echo 'Upper Bits: ' . $uuid->getMostSignificantBits() . "\n";
echo 'Lower Bits: ' . $uuid->getLeastSignificantBits() . "\n";

你得到:

Upper Bits: 12914855512537121056
Lower Bits: 13505861215413436558

使用这些方法您可以获得Moontoast\Math\BigNumber 对象,因此您可以获得它的值或转换为不同的基数:

$higher = $uuid->getMostSignificantBits();
echo 'Upper Bits 10-base: ' . $higher->getValue() . "\n";
echo 'Upper Bits hex: ' . $higher->convertToBase(16) . "\n";

你得到:

Upper Bits 10-base: 12914855512537121056
Upper Bits hex: b33ac8a9ae454120

您也可以使用已经转换为十六进制的$uuid->getMostSignificantBitsHex()$uuid->getLeastSignificantBitsHex()

【讨论】:

  • 我无法在这个项目中使用 Composer。如果没有它,我该如何设置这个库?
  • 您可以在本地使用 Composer,然后上传文件。其他方式,您可以从 GitHub 手动下载,然后设置自动加载器。
  • 我已经接受了您的回答,因为它是第一个正确回答我的问题的人,但不同的答案提供了一种转换方法,其开销要少得多,我已经给予赏金。
【解决方案2】:

如果您不想使用其他答案中提到的库,则下面的代码将适用于支持 64 位整数的 php 版本。这就是 Java 的 UUID.fromString() 方法所做的。

<?php
PHP_INT_MAX > 2147483647 or exit("Need php version which supports 64-bit integer\n");

$uuid = $argv[1];
$components = explode("-", $uuid);
count($components) == 5 or exit("$uuid is not a valid UUID\n");

$msb = intval($components[0], 16);
$msb <<= 16;
$msb |= intval($components[1], 16);
$msb <<= 16;
$msb |= intval($components[2], 16);

$lsb = intval($components[3], 16);
$lsb <<= 48;
$lsb |= intval($components[4], 16);

echo "UUID: $uuid\n";
echo "MSB: $msb\n";
echo "LSB: $lsb\n";
?>

示例运行:

~ $ php uuid.php b33ac8a9-ae45-4120-bb6e-7537e271808e
UUID: b33ac8a9-ae45-4120-bb6e-7537e271808e
MSB: -5531888561172430560
LSB: -4940882858296115058

【讨论】:

  • 鉴于简单和小代码食物打印,我将赏金奖励给你。感谢您的帮助!
【解决方案3】:

这个repo 可以帮助你。 对于最高有效位 this method,对于最低有效位 this method

【讨论】:

  • 不只是链接到资源,您应该将相关代码添加到 SO 答案中,以防将来特定链接中断或资源被移动。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-22
  • 2018-12-10
  • 2017-10-10
  • 2010-12-09
  • 1970-01-01
  • 2013-03-07
相关资源
最近更新 更多