import binascii


def bitarray_to_base64(b, url_safe=False):
    """Convert a bitarray to a base64 encoded string."""
    # Get the bytes
    bytes_ = b.tobytes()
    
    # Convert it to a string
    string = binascii.b2a_base64(bytes_).decode('ascii').rstrip('\n')
    mod = len(string) % 3
    if mod:
        string += '=' * (3 - mod)
    
    # Make it url-safe
    if url_safe:
        string = string.replace('+','-').replace('/','_')
    
    # Return the string
    return string