Search code examples
c++base32

base32 conversion in C++


does anybody know any commonly used library for C++ that provides methods for encoding and decoding numbers from base 10 to base 32 and viceversa?

Thanks, Stefano


Solution

  • Did you mean "base 10 to base 32", rather than integer to base32? The latter seems more likely and more useful; by default standard formatted I/O functions generate base 10 string format when dealing with integers.

    For the base 32 to integer conversion the standard library strtol() function will do that. For the reciprocal, you don't need a library for something you can easily implement yourself (not everything is a lego brick).

    Here's an example, not necessarily the most efficient, but simple;

    #include <cstring>
    #include <string>
    
    long b32tol( std::string b32 )
    {
        return strtol( b32.c_str(), 0, 32 ) ;
    }
    
    std::string itob32( long i )
    {
        unsigned long u = *(reinterpret_cast<unsigned long*>)( &i ) ;
        std::string b32 ;
    
        do
        {
            int d = u % 32 ;
            if( d < 10 )
            {
                b32.insert( 0, 1, '0' + d ) ;
            }
            else
            {
                b32.insert( 0, 1, 'a' + d - 10 ) ;
            }
    
            u /= 32 ;
    
        } while( u > 0 );
    
        return b32 ;
    }
    
    
    #include <iostream>
    
    int main() 
    { 
        long i = 32*32*11 + 32*20 + 5 ; // BK5 in base 32
        std::string b32 = itob32( i ) ;
        long ii = b32tol( b32 ) ;
    
        std::cout << i << std::endl ;    // Original
        std::cout << b32 << std::endl ;  // Converted to b32
        std::cout << ii << std::endl ;   // Converted back
    
        return 0 ;
    }