bindec
(PHP 4, PHP 5)
bindec — Binary to decimal
Описание
Returns the decimal equivalent of the binary number represented by the binary_string argument.
bindec() converts a binary number to an integer or, if needed for size reasons, float.
Список параметров
- binary_string
-
The binary string to convert
Возвращаемые значения
The decimal value of binary_string
Список изменений
Версия | Описание |
---|---|
Since 4.1.0 | The function can now convert numbers that are too large to fit into the platforms integer type, larger values are returned as float in that case. |
Примеры
Пример #1 bindec() example
<?php
echo bindec('110011') . "\n";
echo bindec('000110011') . "\n";
echo bindec('111');
?>
Результат выполнения данного примера:
51 51 7
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Математические расширения
- Математические функции
- abs
- acos
- acosh
- asin
- asinh
- atan2
- atan
- atanh
- base_convert
- bindec
- ceil
- cos
- cosh
- decbin
- dechex
- decoct
- deg2rad
- exp
- expm1
- floor
- fmod
- getrandmax
- hexdec
- hypot
- intdiv
- is_finite
- is_infinite
- is_nan
- lcg_value
- log10
- log1p
- log
- max
- min
- mt_getrandmax
- mt_rand
- mt_srand
- octdec
- pi
- pow
- rad2deg
- rand
- round
- sin
- sinh
- sqrt
- srand
- tan
- tanh
Коментарии
## 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)
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));
}
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);
}
?>
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.
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;
}
} ?>