【问题标题】:Increment hex value (little endian?) in PHP在 PHP 中增加十六进制值(小端?)
【发布时间】:2014-12-21 18:06:59
【问题描述】:

在传入的 UDP 数据包中,我有十六进制值 b70500。这实际上是一个序列号 (1463)。在以相同格式 (b80500) 将其发送回服务器之前,我需要增加此值。

如何在 PHP 中将值加一?

使用建议的代码here 我能够将十六进制值转换为整数并将其加一:

$original_hex = 'b70500';                                        // 1463
$original_int = unpack("H*", strrev(pack("H*", $original_hex))); // 0005b7
$incremented_int = hexdec($original_int[1]) + 1;                 // 1464
$incremented_hex = ?                                             // Expected result: b80500

...但我不知道如何将其转换回十六进制。也许有更有效的方法?

【问题讨论】:

标签: php integer hex increment


【解决方案1】:

这并不漂亮,我敢打赌有更有效的方法可以做到这一点,但它确实有效:

function increment_hex($hex) {
  $original_hex = $hex;
  $original_int = unpack("H*", strrev(pack("H*", $original_hex)));
  $incremented_int = hexdec($original_int[1]) + 1;
  $incremented_hex = dechex($incremented_int);

  $padded_hex = str_pad($incremented_hex, 6, '0', STR_PAD_LEFT);
  $reversed_hex = unpack("H*", strrev(pack("H*", $padded_hex)));

  return $reversed_hex[1];
}

echo "result: " . increment_hex('b70500') . "\n";

result: b80500

【讨论】:

    【解决方案2】:

    hexdec()dechex()。您不必解压该值。

    $incremented = dechex(hexdec('b70500') + 1);
    

    【讨论】:

    • 谢谢!但是,该 sn-p 返回 b70501,(对应于 67000)。预期结果是b80500 (1464)。更具体地说:服务器需要相同格式的数字,5b8(也对应于 1464 不会做...)。
    猜你喜欢
    • 2010-10-05
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    相关资源
    最近更新 更多