-3

I have a variable containing a value in bit, ex 10000000 representing 10mb. I'd like to write a function that from a value in bit, return a string with the right unit and correctly converted.

Example if I use 52200000, it returns 52.2mb.

I don't know how to proceed. Can someone help, thank you

Nicox11
  • 96
  • 1
  • 1
  • 7

2 Answers2

1
def humanize(n):
   base=1000.0   # replace with 1024 if you want kib Mib etc
   letters=['','k','M','G','T','P','E','Z','Y'] 
   f=float(n)
   for x in letters:
       if f < base: break
       f /= base
   return '{:.3}{}b'.format(f,x) # change {}b to {}ib if working with kib etc.

These days Mb normally refers to a decimal million bytes and Mib normally refers to 1024*1024 of them. This code is trivial to switch.

nigel222
  • 7,582
  • 1
  • 14
  • 22
0
def bytesto(bytes, to, bsize=1000):
    a = {'k' : 1, 'm': 2, 'g' : 3, 't' : 4, 'p' : 5, 'e' : 6 }
    r = float(bytes)
    for i in range(a[to]):
        r = r / bsize
    return(r)

you can use above function to convert bytes to kb,mb,gb,tb

  • Convert bytes to KB print(bytesto(314575262000000, 'k')) # 314575262000.0 KB
  • Convert bytes to MB print(bytesto(314575262000000, 'm')) # 314575262.0 MB
  • Convert bytes to TB print(bytesto(314575262000000, 't')) # 314.575262 TB
Himanshu dua
  • 2,496
  • 1
  • 20
  • 27