Reputation: 89
I would like to use base_convert function to convert 60 bit binary data to Hex code as follows. But the result is not correct. The output of the code below is 4e08556312ffc00 but the correct output is 4E08556312FFBFF. Can anybody tell me why? is 60 bit too large to the function?
echo "The beacon ID in Hexadecimal is".base_convert
("010011100000100001010101011000110001001011111111101111111111",2, 16);
Thank
Upvotes: 1
Views: 5038
Reputation: 12015
It is the larger of:
Typical PHP implementations use IEEE 754 for implementing floating point numbers, which has a 53-bit significand, so the typical limit for 32-bit environments is 2⁵³ (0x20000000000000
) and for 64-bit environments, the limit is 2⁶³-1 (0x7fffffffffffffff
).
There’s a trivial solution if you have the PHP gmp extension ( http://php.net/gmp ):
$hexNumber = gmp_strval( gmp_init( $binNumber, 2 ), 16 ) ;
If you have the bc extension (http://php.net/bc ), my (free & open source) WeirdoCustomDigits module will do conversions with arbitrary bases and arbitrary digit characters, without limitation.
If you're simply converting between base 2 and base 16, as with your example, you can get by without bc or gmp. See the source in the WeirdoCustomDigits module for WeirdoCustomDigits::binFromHex() and WeirdoCustomDigits::hexFromBin().
Upvotes: 0
Reputation: 1
My tests reveal a loss of precision over 43bits.
I work on a Win XP base + easyphp 3.1.81 with default settings.
I use this base_convert for a genealogical application, and the limit of 43 generations is - sometimes - not enough.
Upvotes: 0
Reputation: 437474
I have posted an implementation of a base conversion function without such limits in my answer to another question here.
Upvotes: 2
Reputation: 68810
According to base_convert and floating numbers documentation, base_convert
will lose precision on large numbers.
Instead of, you can use bin2hex
, which is not limited (this function use and return strings)
Upvotes: 0