1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[PHP] 16進数表現の罠

Last updated at Posted at 2021-06-28

PHP5までは特に問題なかったところ、PHP7に移行して(今更)発覚した問題。

huh.php
<?php
var_dump(dechex(0xfedcba9876543210));

string(16) "fedcba9876543000"

…はぅ?

omg.php
<?php
var_dump(0xfedcba9876543210);

float(1.8364758544493E+19)

まさかのfloat。

max.php
<?php
var_dump(0x7fffffffffffffff);

int(9223372036854775807)

正数なら問題ないらしい不思議。

shift.php
<?php
var_dump(1<<63);

int(-9223372036854775808)

シフト演算で突き押し作戦。

ok.php
<?php
var_dump(dechex(0xf<<60|0xedcba9876543210));

string(16) "fedcba9876543210"

強引に解決。

PHP8では…

huh.php
<?php
var_dump(dechex(0xfedcba9876543210));

Fatal error: Uncaught TypeError: dechex(): Argument #1 ($num) must be of type int, float given

叱られた…

ok.php
<?php
var_dump(dechex(0xf<<60|0xedcba9876543210));

string(16) "fedcba9876543210"

原因は同じなので、同じく強引に解決可。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?