Python Program to convert bytes to Kilobytes, Megabytes, Gigabytes and Terabytes

Bytes:- A Byte is just 8 Bits and is the smallest unit of memory .
One byte can store one character.

1 byte = 8 bits.

1000 bytes = 1 KiloBytes
1000000 bytes =1 megabytes
1000000000 bytes = 1 Gigabyte
1000000000000 bytes = 1 terabytes


Program to convert bytes to Kilobytes, Megabytes, Gigabytes and Terabytes in

def convert_bytes(bytes_number):
    tags = [ "Byte", "Kilobyte", "Megabyte", "Gigabyte", "Terabyte" ]
 
    i = 0
    double_bytes = bytes_number
 
    while (i < len(tags) and  bytes_number >= 1024):
            double_bytes = bytes_number / 1024.0
            i = i + 1
            bytes_number = bytes_number / 1024
 
    return str(round(double_bytes, 2)) + " " + tags[i]
 
 
print(convert_bytes(4896587482345))
print(convert_bytes(9876524362))
print(convert_bytes(10248000))
print(convert_bytes(1048576))
print(convert_bytes(1024000))
print(convert_bytes(475445))
print(convert_bytes(1024))
print(convert_bytes(75))
print(convert_bytes(0))

 


Output:-

4.45 Terabyte
9.2 Gigabyte
9.77 Megabyte
1.0 Megabyte
1000.0 Kilobyte
464.3 Kilobyte
1.0 Kilobyte
75 Byte
0 Byte

 

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *