Convert bytes to KB,MB and GB using Java Program
In many cases, we might get the memory or size of the file/table in bytes.The simple java program can able to convert the bytes to KB,MB and GB using traditional way of calculation.Before we look into the program, lets understand the conversion method to change the memory unit from one to another.
Memory units
The data (File,Image,text,number..etc) is stored in the memory in the form of bits such as 0 & 1. Here the memory units helps to measure the storage of those data. The units are defined as below.
- 1 Byte is equal to 8 bits
- 1 Kilobyte(KB) is equal to 1024 Bytes
- 1 Megabyte(MB) is equal to 1024 Kilobytes
- 1 Gigabyte(GB) is equal to 1024 Megabytes
- 1 Terabyte(TB) is equal to 1024 Gigabytes
- 1 Petabyte(PB) is equal to 1024 Terabytes.
For example, we have a file size in terms of bytes and it is more than 1024 bytes. In that case, we can just divide that value by 1024 to get the size in Kilobytes(KB).
1 2 |
File size = 3200 Bytes Calculate File size in KB = 3200/1024 => 3.125 KB |
Similarly if we divide the Kilobytes by 1024 , It will give the Megabytes(MB). The same calculation is applicable for the remaining units.
Java Program to convert bytes to KB,MB and GB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class ConvertSize{ public static void main(String[] args) { double size_bytes=1999901221; String cnt_size; double size_kb = size_bytes /1024; double size_mb = size_kb / 1024; double size_gb = size_mb / 1024 ; if (size_gb > 0){ cnt_size = size_gb + " GB"; }else if(size_mb > 0){ cnt_size = size_mb + " MB"; }else{ cnt_size = size_kb + " KB"; } System.out.println("Converted Size: " + cnt_size); } } |
Output:
1 |
Converted Size: 1.862553154118359 GB |
Recommended Articles