Python Forum
converting a number from bytes to float and back
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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#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)
Reply
#3
Read This blog....
https://os.mbed.com/forum/helloworld/top...ment-54720
Reply
#4
that blog is showing C code. why do you think i need to read that?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  converting an int to bytes Skaperen 3 1,058 Jun-15-2023, 10:24 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020