python 中的多位操作

Multiple bit manipulation in python

我有一个包含位值的变量,例如 10000000 代表 10mb。我想编写一个函数,该函数从位值 return 具有正确单位并正确转换的字符串。

例如,如果我使用 52200000,它 returns 52.2mb。

我不知道如何进行。有人可以帮忙吗,谢谢

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

  • 将字节转换为 KB print(bytesto(314575262000000, 'k')) # 314575262000.0 KB
  • 将字节转换为 MB print(bytesto(314575262000000, 'm')) # 314575262.0 MB
  • 将字节转换为 TB print(bytesto(314575262000000, 't')) # 314.575262 TB
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.

现在Mb一般指十进制百万字节,Mib一般指1024*1024。这段代码很容易切换。