effective solution: base32 encoding in php

前端 未结 3 1583
温柔的废话
温柔的废话 2021-01-03 04:26

I am looking for a base32 function/class for php. the different classes and function that i found are all very ineffective. I ran a benchmark and came to the following resul

3条回答
  •  猫巷女王i
    2021-01-03 05:04

    For Base32 in PHP, you can try my implementation here:

    https://github.com/ademarre/binary-to-text-php

    Copied from the Base32 example in the README file:

    // RFC 4648 base32 alphabet; case-insensitive
    $base32 = new Base2n(5, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', FALSE, TRUE, TRUE);
    $encoded = $base32->encode('encode this');
    // MVXGG33EMUQHI2DJOM======
    

    It's not slow, and it may or may not be faster than the class you benchmarked, but it will not be as fast as a built-in PHP function like base64_encode(). If that is very important to you, and you don't really care about Base32 encoding, then you should just use hexadecimal. You can encode hexadecimal with native PHP functions, and it is case-insensitive.

    $encoded = bin2hex('encode this'); // 656e636f64652074686973
    $decoded = pack('H*', $encoded);   // encode this
    
    // Alternatively, as of PHP 5.4...
    $decoded = hex2bin($encoded);      // encode this
    

    The downside to hexadecimal is that there is more data inflation compared to Base32. Hexadecimal inflates the data 100%, while Base32 inflates the data about 60%.

提交回复
热议问题