
def to_hex(text):
    return text.encode().hex()

def from_hex(hex_text):
    try:
        checkHex(hex_text,'Input')
        return bytes.fromhex(hex_text).decode()
    except UnicodeDecodeError as e:
        return str(e)
    except ValueError as e:
        return str(e)

def hex_ope(text, to_from:bool):
    if to_from:
        return to_hex(text)
    else:
        return from_hex(text)

def checkHex(text,cheking):
    if len(text)%2 != 0:
        raise ValueError(f"{cheking}: Invalid hex length")
    hexdigits = '0123456789abcdefABCDEF'
    for i in text:
        if i not in hexdigits:
            raise ValueError(f"{cheking}: Invalid hex")
    return True
