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

base_convert

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

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

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

function.base-convert.php

base_convert

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

base_convertПретвори број помеѓу произволни основи

= NULL

base_convert(string $num, int $from_base, int $to_base): string

Враќа стринг кој содржи num претставен во основа to_base. Основата во која num е дадена е специфицирана во from_base. И двете from_base and to_base мора да бидат помеѓу 2 и 36, вклучително. Цифрите во броеви со основа повисока од 10 ќе бидат претставени со буквите a-z, каде a значи 10, b значи 11 и z значи 35. Големината на буквите не е важна, т.е. num се толкува нечувствително на големината на буквите.

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

base_convert() може да изгуби прецизност на големи броеви поради својства поврзани со внатрешниот float тип што се користи. Ве молиме видете го делот Броеви со подвижна запирка во прирачникот за поспецифични информации и ограничувања.

Параметри

num

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

from_base

Основата num е во

to_base

Основата за конвертирање num to

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

num конвертиран во основа to_base

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

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

Примери

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

<?php
$hexadecimal
= 'a37334';
echo
base_convert($hexadecimal, 16, 2);
?>

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

101000110111001100110100

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

  • intval() не-нумерички најлеви карактери Пример

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

PHPCoder на niconet2k точка com
пред 14 години
Convert an arbitrarily large number from any base to any base.

string convBase(string $numberInput, string $fromBaseInput, string $toBaseInput)
$numberInput number to convert as a string
$fromBaseInput base of the number to convert as a string
$toBaseInput base the number should be converted to as a string
examples for $fromBaseInput and $toBaseInput
'0123456789ABCDEF' for Hexadecimal (Base16)
'0123456789' for Decimal (Base10)
'01234567' for Octal (Base8)
'01' for Binary (Base2) 
You can really put in whatever you want and the first character is the 0.
Examples:

<?php 
convBase('123', '0123456789', '01234567'); 
//Convert '123' from decimal (base10) to octal (base8).
//result: 173

convBase('70B1D707EAC2EDF4C6389F440C7294B51FFF57BB', '0123456789ABCDEF', '01');
//Convert '70B1D707EAC2EDF4C6389F440C7294B51FFF57BB' from hexadecimal (base16) to binary (base2).
//result: 
//111000010110001110101110000011111101010110000101110
//110111110100110001100011100010011111010001000000110
//001110010100101001011010100011111111111110101011110
//111011

convBase('1324523453243154324542341524315432113200203012', '012345', '0123456789ABCDEF');
//Convert '1324523453243154324542341524315432113200203012' from senary (base6) to hexadecimal (base16).
//result: 1F9881BAD10454A8C23A838EF00F50

convBase('355927353784509896715106760','0123456789','Christopher');
//Convert '355927353784509896715106760' from decimal (base10) to undecimal (base11) using "Christopher" as the numbers.
//result: iihtspiphoeCrCeshhorsrrtrh

convBase('1C238Ab97132aAC84B72','0123456789aAbBcCdD', '~!@#$%^&*()');
//Convert'1C238Ab97132aAC84B72' from octodecimal (base18) using '0123456789aAbBcCdD' as the numbers to undecimal (base11) using '~!@#$%^&*()' as the numbers.
//result: !%~!!*&!~^!!&(&!~^@#@@@&

function convBase($numberInput, $fromBaseInput, $toBaseInput)
{
    if ($fromBaseInput==$toBaseInput) return $numberInput;
    $fromBase = str_split($fromBaseInput,1);
    $toBase = str_split($toBaseInput,1);
    $number = str_split($numberInput,1);
    $fromLen=strlen($fromBaseInput);
    $toLen=strlen($toBaseInput);
    $numberLen=strlen($numberInput);
    $retval='';
    if ($toBaseInput == '0123456789')
    {
        $retval=0;
        for ($i = 1;$i <= $numberLen; $i++)
            $retval = bcadd($retval, bcmul(array_search($number[$i-1], $fromBase),bcpow($fromLen,$numberLen-$i)));
        return $retval;
    }
    if ($fromBaseInput != '0123456789')
        $base10=convBase($numberInput, $fromBaseInput, '0123456789');
    else
        $base10 = $numberInput;
    if ($base10<strlen($toBaseInput))
        return $toBase[$base10];
    while($base10 != '0')
    {
        $retval = $toBase[bcmod($base10,$toLen)].$retval;
        $base10 = bcdiv($base10,$toLen,0);
    }
    return $retval;
}
?>
Анонимен
пред 7 години
While not immediately clear from the description above, a negative sign is also "silently ignored".

base_convert("-12", 10, 10)   =>   12
lindsay на bitleap точка com
21 години пред
If you need to use base_convert with numbers larger then 32 bit, the following gmp implementation of base_convert should work.

<?php

/*use gmp library to convert base. gmp will convert numbers > 32bit*/
function gmp_convert($num, $base_a, $base_b)
{
        return gmp_strval ( gmp_init($num, $base_a), $base_b );
}

?>
ardavies на tiscali точка co точка uk
пред 11 години
In order to convert base 26 (hexavigesimal) of just alphanumeric characters (A-Z), wthout integers, (as descibed at http://en.wikipedia.org/wiki/Hexavigesimal), I found this to be useful:

function base_convert_alpha(  $str,  $from,  $to  )
{
    $r = range( 'A', 'Z' );
    $clean = str_replace( $r, array_keys($r), $str );
    return base_convert( $clean, $from, $to );
}

echo base_convert_alpha(  "BAC",  26,  10  );

//$clean = 102 which then returns 678
ohcc на 163 dot com
пред 8 години
<?php
    $v = base_convert(3.14, 10, 10);
    var_dump($v);
?>

output: string(3) "314"
cyrilbele на yahoo точка fr
пред 16 години
If you want to do sharding, at some point you will need to decide which shard to target. Here is a simple function to assign the data to a particular shard based on a key (usually identifier of the row)

Here is a simple function to get the shard based on the key and the number of shards available

<?php
function getShard($key,$nbShards) {
    $num = substr(base_convert(sha1($key), 16, 10),4,6);
    return $num%$nbShards;
}
?>
На оваа страница

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

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

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

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

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