from binascii import unhexlify

def to_big_endian_binary(val):
    # one (1) hex digit per four (4) bits
    width = val.bit_length()

    # unhexlify wants an even multiple of eight (8) bits, but we don't
    # want more digits than we need (hence the ternary-ish 'or')
    width += 8 - ((width % 8) or 8)

    # format width specifier: four (4) bits per hex digit
    fmt = '%%0%dx' % (width // 4)

    # prepend zero (0) to the width, to zero-pad the output
    return unhexlify(fmt % val)

def to_big_endian_binary(val):
    s = '%x' % val
    if len(s) & 1:
        s = '0' + s
    return s.decode('hex')

improve to_big_endian_binary function