converting a number from bytes to float and back - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: News and Discussions (https://python-forum.io/forum-31.html) +--- Thread: converting a number from bytes to float and back (/thread-22331.html) |
converting a number from bytes to float and back - Skaperen - Nov-08-2019 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. RE: converting a number from bytes to float and back - scidam - Nov-10-2019 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) RE: converting a number from bytes to float and back - LeanbridgeTech - Nov-11-2019 Read This blog.... https://os.mbed.com/forum/helloworld/topic/2053/?page=1#comment-54720 RE: converting a number from bytes to float and back - Skaperen - Nov-12-2019 that blog is showing C code. why do you think i need to read that? |