<?php
/*
* Die Lektion dieses Beispiels liegt in der Ausgabe,
* und nicht im PHP-Code selbst.
*/
$magnitude_lower = pow(2, (PHP_INT_SIZE * 8) - 2);
p($magnitude_lower - 1);
p($magnitude_lower, 'Beachte den Überlauf, auch in den folgenden Fällen!');
p(PHP_INT_MAX, 'PHP_INT_MAX');
p(~PHP_INT_MAX, 'interpretiert als eins mehr als PHP_INT_MAX');
if (PHP_INT_SIZE == 4) {
$note = 'interpretiert als größte vorzeichenlose Ganzzahl';
} else {
$note = 'interpretiert als größte vorzeichenlose Ganzzahl (18446744073709551615),
aber ungenau aufgrund mangelnder Gleitkommagenauigkeit';
}
p(-1, $note);
function p($input, $note = '') {
echo "Eingabe: $input\n";
$format = '%0' . (PHP_INT_SIZE * 8) . 'b';
$bin = sprintf($format, $input);
echo "Binär: $bin\n";
ini_set('precision', 20); // zur Lesbarkeit auf 64bit-Systemen
$dec = bindec($bin);
echo 'bindec(): ' . $dec . "\n";
if ($note) {
echo "HINWEIS: $note\n";
}
echo "\n";
}
?>
Das oben gezeigte Beispiel erzeugt auf 32-Bit-Systemen folgende Ausgabe:
Eingabe: 1073741823
Binär: 00111111111111111111111111111111
bindec(): 1073741823
Eingabe: 1073741824
Binär: 01000000000000000000000000000000
bindec(): 1073741824
HINWEIS: Beachte den Überlauf, auch in den folgenden Fällen!
Eingabe: 2147483647
Binär: 01111111111111111111111111111111
bindec(): 2147483647
HINWEIS: PHP_INT_MAX
Eingabe: -2147483648
Binär: 10000000000000000000000000000000
bindec(): 2147483648
HINWEIS: interpretiert als eins mehr als PHP_INT_MAX
Eingabe: -1
Binär: 11111111111111111111111111111111
bindec(): 4294967295
HINWEIS: interpretiert als größte vorzeichenlose Ganzzahl
Das oben gezeigte Beispiel erzeugt auf 64-Bit-Systemen folgende Ausgabe:
Eingabe: 4611686018427387903
Binär: 0011111111111111111111111111111111111111111111111111111111111111
bindec(): 4611686018427387903
Eingabe: 4611686018427387904
Binär: 0100000000000000000000000000000000000000000000000000000000000000
bindec(): 4611686018427387904
HINWEIS: Beachte den Überlauf, auch in den folgenden Fällen!
Eingabe: 9223372036854775807
Binär: 0111111111111111111111111111111111111111111111111111111111111111
bindec(): 9223372036854775807
HINWEIS: PHP_INT_MAX
Eingabe: -9223372036854775808
Binär: 1000000000000000000000000000000000000000000000000000000000000000
bindec(): 9223372036854775808
HINWEIS: interpretiert als eins mehr als PHP_INT_MAX
Eingabe: -1
Binär: 1111111111111111111111111111111111111111111111111111111111111111
bindec(): 18446744073709551616
HINWEIS: interpretiert als größte vorzeichenlose Ganzzahl (18446744073709551615),
aber ungenau aufgrund mangelnder Gleitkommagenauigkeit