Convert a binary number to Base 64

前端 未结 4 1398
陌清茗
陌清茗 2021-01-15 12:14

I know this is a pretty silly question, but I don\'t know what to do.

I have an arbitrary binary number, say,

100100000011001000000010010000001000001         


        
相关标签:
4条回答
  • 2021-01-15 12:45

    Length of a string in example is 160. It makes me think that it holds info about 160/8 characters. So,

    1. split string into parts, each part holds 8 binary digits and describes single character
    2. convert each part into a decimal integer
    3. build a string from characters, that are made from ASCII codes from 2nd step

    This will work with strings with size n*8. For other strings (e.g., 12 binary digits) it will give unexpected results.

    Code:

    function bin2base64($bin) {
        $arr = str_split($bin, 8);
        $str = '';
        foreach ( $arr as $binNumber ) {
            $str .= chr(bindec($binNumber));
        }
        return base64_encode($str);
    }
    
    $bin = '1001000000110010000000100100000010000011000000010001000001011000110000110000011100011100000011000000010010011000100000000000000100100000010110001100001000000111';
    echo bin2base64($bin);
    

    Result:

    kDICQIMBEFjDBxwMBJiAASBYwgc=
    

    Here's also function for decoding it back to string of binary digits:

    function base64bin($str) {
        $result = '';
        $str = base64_decode($str);
        $len = strlen($str);
        for ( $n = 0; $n < $len; $n++ ) {
            $result .= str_pad(decbin(ord($str[$n])), 8, '0', STR_PAD_LEFT);
        }
        return $result;
    }
    
    var_dump(base64bin(bin2base64($bin)) === $bin);
    

    Result:

    boolean true
    
    0 讨论(0)
  • 2021-01-15 12:47

    PHP has a built in base 64 encoding function, see documentation here. If you want the decimal value of the binary string first use bin2dec, there are similar functions for hexadecimals by the way. The documentation is your friend here.

    [EDIT]

    I might have misunderstood your question, if you want to convert between actual bases (base 2 and 64) use base_convert

    0 讨论(0)
  • 2021-01-15 12:53

    To convert a binary number (2 base) to a 64 base use the base_convert function.

    $number = 1001000000110010000000100100000010000011000000010001000001011000110000110000011100011100000011000000010010011000100000000000000100100000010110001100001000000111;
    base_convert ($number , 2, 64);
    

    0 讨论(0)
  • 2021-01-15 13:02
    $number = 1001000000110010000000100100000010000011000000010001000001011000110000110000011100011100000011000000010010011000100000000000000100100000010110001100001000000111;
    echo base64_encode ($number);
    

    This is if you want the exact string be converted into Base 64.

    0 讨论(0)
提交回复
热议问题