PHP.mk документација

bindec

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.bindec.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.bindec.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
bindec

Референца за `function.bindec.php` со подобрена типографија и навигација.

function.bindec.php

bindec

(PHP 4, PHP 5, PHP 7, PHP 8)

bindecБинарно во децимално

= NULL

bindec(string $binary_string): int|float

Враќа децимален еквивалент на бинарниот број претставен со binary_string argument.

bindec() конвертира бинарен број во int или, ако е потребно поради големината, float.

bindec() ги толкува сите binary_string вредности како unsigned integers. Ова е затоа што bindec() го гледа најзначајниот бит како уште еден ред на големина наместо како знак бит.

Параметри

binary_string

Бинарниот стринг за конвертирање. Сите невалидни карактери во binary_string се тивко игнорирани. Од PHP 7.4.0, давањето на било какви невалидни карактери е депрецирано.

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

Параметарот мора да биде стринг. Користењето на други типови на податоци ќе произведе неочекувани резултати.

Вратени вредности

Децималната вредност на binary_string

Дневник на промени

Верзија = NULL
7.4.0 Оваа функција сега може да се повика без никакви параметри. Претходно, се бараше барем еден параметар.

Примери

Пример #1 bindec() example

<?php
echo bindec('110011') . "\n";
echo
bindec('000110011') . "\n";

echo
bindec('111');
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

51
51
7

Пример #2 bindec() ги толкува влезовите како unsigned integers

<?php
/*
* The lesson from this example is in the output
* rather than the PHP code itself.
*/

$magnitude_lower = pow(2, (PHP_INT_SIZE * 8) - 2);
p($magnitude_lower - 1);
p($magnitude_lower, 'See the rollover? Watch it next time around...');

p(PHP_INT_MAX, 'PHP_INT_MAX');
p(~PHP_INT_MAX, 'interpreted to be one more than PHP_INT_MAX');

if (
PHP_INT_SIZE == 4) {
$note = 'interpreted to be the largest unsigned integer';
} else {
$note = 'interpreted to be the largest unsigned integer
(18446744073709551615) but skewed by float precision'
;
}
p(-1, $note);


function
p($input, $note = '') {
echo
"input: $input\n";

$format = '%0' . (PHP_INT_SIZE * 8) . 'b';
$bin = sprintf($format, $input);
echo
"binary: $bin\n";

ini_set('precision', 20); // For readability on 64 bit boxes.
$dec = bindec($bin);
echo
'bindec(): ' . $dec . "\n";

if (
$note) {
echo
"NOTE: $note\n";
}

echo
"\n";
}
?>

Пример #3 Бинарно поместување на цели броеви

input:        1073741823
binary:       00111111111111111111111111111111
bindec():     1073741823

input:        1073741824
binary:       01000000000000000000000000000000
bindec():     1073741824
NOTE:         See the rollover?  Watch it next time around...

input:        2147483647
binary:       01111111111111111111111111111111
bindec():     2147483647
NOTE:         PHP_INT_MAX

input:        -2147483648
binary:       10000000000000000000000000000000
bindec():     2147483648
NOTE:         interpreted to be one more than PHP_INT_MAX

input:        -1
binary:       11111111111111111111111111111111
bindec():     4294967295
NOTE:         interpreted to be the largest unsigned integer

Излез од горниот пример на машини со 32 бита:

input:        4611686018427387903
binary:       0011111111111111111111111111111111111111111111111111111111111111
bindec():     4611686018427387903

input:        4611686018427387904
binary:       0100000000000000000000000000000000000000000000000000000000000000
bindec():     4611686018427387904
NOTE:         See the rollover?  Watch it next time around...

input:        9223372036854775807
binary:       0111111111111111111111111111111111111111111111111111111111111111
bindec():     9223372036854775807
NOTE:         PHP_INT_MAX

input:        -9223372036854775808
binary:       1000000000000000000000000000000000000000000000000000000000000000
bindec():     9223372036854775808
NOTE:         interpreted to be one more than PHP_INT_MAX

input:        -1
binary:       1111111111111111111111111111111111111111111111111111111111111111
bindec():     18446744073709551616
NOTE:         interpreted to be the largest unsigned integer
              (18446744073709551615) but skewed by float precision

Белешки

Забелешка:

Функцијата може да конвертира броеви што се преголеми за да се вклопат во платформата int тип, поголемите вредности се враќаат како float во тој случај.

Види Исто така

  • decbin() - Децимално во бинарно
  • octdec() - Октално во децимално
  • hexdec() - Хексадецимално во децимално
  • base_convert() - Конвертирај број помеѓу произволни бази

Белешки од корисници 5 белешки

info at rickdg dot nl
пред 15 години
Two functions to convert 16bit or 8bit binary to integer using two's complement. If input exceeds maximum bits, false is returned. Function is easily scalable to x bits by changing the hexadecimals.

<?php function _bin16dec($bin) {
    // Function to convert 16bit binary numbers to integers using two's complement
    $num = bindec($bin);
    if($num > 0xFFFF) { return false; }
    if($num >= 0x8000) {
        return -(($num ^ 0xFFFF)+1);
    } else {
        return $num;
    }
}

function _bin8dec($bin) {
    // Function to convert 8bit binary numbers to integers using two's complement
    $num = bindec($bin);
    if($num > 0xFF) { return false; }
    if($num >= 0x80) {
        return -(($num ^ 0xFF)+1);
    } else {
        return $num;
    }
} ?>
martin на punix точка de
пред 22 години
## calculate binary with "shift-method" ##

<?php
function dec2bin($decimal_code){
 for($half=($decimal_code);$half>=1;$half=(floor($half))/2){
   if(($half%2)!=0){
    $y.=1;
   }
   else{
    $y.=0;
   }
  }
 $calculated_bin=strrev($y);
 return $calculated_bin;
}
?>

## example ##

[bin] 123 = [dec] 1111011

e.g.
123/2 = 61,5 => 1
61/2  = 30,5 => 1
30/2  = 15   => 0
15/2  = 7,5  => 1
7/2   = 3,5  => 1
3/2   = 1,5  => 1
1/2   = 0,5  => 1
(0/2   = 0    finish)
gwbdome на freenet точка de
21 години пред
i think a better method than the "shift-method" is my method ^^...
here it comes:

function convert2bin($string) {
     $finished=0;
     $base=1;
     if(preg_match("/[^0-9]/", $string)) {
         for($i=0; $string!=chr($i); $i++);
         $dec_nr=$i;
     }
     else $dec_nr=$string;
     while($dec_nr>$base) {
         $base=$base*2;
         if($base>$dec_nr) {
             $base=$base/2;
             break;
         }
     }
     while(!$finished) {
         if(($dec_nr-$base)>0) {
             $dec_nr=$dec_nr-$base;
             $bin_nr.=1;
             $base=$base/2;
         }
         elseif(($dec_nr-$base)<0) {
             $bin_nr.=0;
             $base=$base/2;
         }
         elseif(($dec_nr-$base)==0) {
             $bin_nr.=1;
             $finished=1;
             while($base>1) {    
                 $bin_nr.=0;
                 $base=$base/2;
             }
         }
     }
     return $bin_nr;
 }

=====================================================

if you want to reconvert it (from binary to string or integer) you can use this function: 

function reconvert($bin_nr) {
     $base=1;
     $dec_nr=0;
     $bin_nr=explode(",", preg_replace("/(.*),/", "$1", str_replace("1", "1,", str_replace("0", "0,", $bin_nr))));
     for($i=1; $i<count($bin_nr); $i++) $base=$base*2;
     foreach($bin_nr as $key=>$bin_nr_bit) {
         if($bin_nr_bit==1) {
             $dec_nr+=$base;
             $base=$base/2;
         }
         if($bin_nr_bit==0) $base=$base/2;
     }
     return(array("string"=>chr($dec_nr), "int"=>$dec_nr));
 }
Испринтај ги сите преостанати податоци на покажувач на gz-датотека
пред 16 години
Binary to Decimal conversion using the BCMath extension..

<?php

function BCBin2Dec($Input='') {
  $Output='0';
  if(preg_match("/^[01]+$/",$Input)) {
    for($i=0;$i<strlen($Input);$i++)
      $Output=BCAdd(BCMul($Output,'2'),$Input{$i});
  }
  return($Output);
}

?>

This will simply convert from Base-2 to Base-10 using BCMath (arbitrary precision calculation).

See also: my 'BCDec2Bin' function on the 'decbin' document.
Enjoy,
Nitrogen.
алан хоган точка ком коса контакт
пред 18 години
The "smartbindec" function I wrote below will convert any binary string (of a reasonable size) to decimal.  It will use two's complement if the leftmost bit is 1, regardless of bit length.  If you are getting unexpected negative answers, try zero-padding your strings with sprintf("%032s", $yourBitString).

<?php
function twoscomp($bin) {
    $out = "";
    $mode = "init";
    for($x = strlen($bin)-1; $x >= 0; $x--) {
        if ($mode != "init")
            $out = ($bin[$x] == "0" ? "1" : "0").$out;
        else {
            if($bin[$x] == "1") {
                $out = "1".$out;
                $mode = "invert";
            }
            else
                $out = "0".$out;
        }
    }
    return $out;
}
function smartbindec($bin) {
    if($bin[0] == 1)
        return -1 * bindec(twoscomp($bin));
    else return (int) bindec($bin);
}
?>
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.