import binascii


def bitarray_to_hex(b):
    """Convert a bitarray to a hexidecimal string."""
    bytes_ = b.tobytes()
    s = binascii.hexlify(bytes_).decode('ascii')
    if b.length() % 8 and not (b.length() % 4):
        return s[:-1]
    return s