Search code examples
phphexdecodeencodebase32

PHP Convert Hext To Base32 And Vice Versa


I am facing problem to convert a hex representation to base 32 and vice versa.

all online convert is JavaScript based, but i can't find any PHP based solution after quite search here and there :(

i have tried base32Encode the hex value, hexdec then base32 encode none of them work actually :(

hex: 686aa8fca1767a5c1cc23b0f982380d6ba6d07ff32fafe8e

base32: NBVKR7FBOZ5FYHGCHMHZQI4A225G2B77GL5P5DQ

what i need here, i need to get (convert) the base32 value from the hex value and vice versa like get the hex value from the base 32.

that's all

Update 1:

following site can encode from hex to base32 in a way what exactly i am looking for but. but i don't know how they do it.. :(

screenshot: enter image description here

thanks


Solution

  • The library suggested by Sammitch works fine (it's RFC 4648 compliant like the site you've posted), but you'll need to add hex2bin()/bin2hex() into the mix to get the results you're after:

    require 'path/to/vendor/autoload.php';
    
    use Base32\Base32;
    
    $hex = '686aa8fca1767a5c1cc23b0f982380d6ba6d07ff32fafe8e';
    
    // Hex to Base32
    
    $to_base32 = Base32::encode(hex2bin($hex)); 
    var_dump($to_base32); // NBVKR7FBOZ5FYHGCHMHZQI4A225G2B77GL5P5DQ=
    
    // Base32 to Hex
    
    $to_hex = bin2hex(Base32::decode($to_base32));
    var_dump($to_hex); // 686aa8fca1767a5c1cc23b0f982380d6ba6d07ff32fafe8e