Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 converting a number from bytes to float and back
#1
if given a number as str, int or float, you can add 1 to it and convert it back to the same type easily:
def inc(num):
    return type(num)(float(num)+1)
how can this be made to also work with bytes? note: it's OK for the return as str to have '.0' in it; it just needs to be str if str was given. i want this to also work if bytes is given; bytes is to be returned when bytes is given.
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Quote
#2
You can implement a decorator to force output type, e.g.



from functools import wraps
def retain_type(f):
    @wraps(f)
    def wrapper(inp):
        res = f(inp)
        if type(res) == type(inp):
            return res
        elif isinstance(res, str):
            return res.encode('utf-8')
        elif isinstance(res, bytes):
            return res.decode('utf-8')
        else:
            raise TypeError("Output type shoud be either bytes or str.")
    return wrapper
@retain_type
def inc(num):
    if isinstance(num, bytes):
        num = num.decode('utf-8')
    return type(num)(float(num)+1)
Quote
#3
Read This blog....
https://os.mbed.com/forum/helloworld/top...ment-54720
Quote
#4
that blog is showing C code. why do you think i need to read that?
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Quote

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)