Converting bytes is a common task, especially during the development of computer programs. In JavaScript, sometimes we need to convert byte units to other units such as KB, MB, or even GB. This article explains how to use JavaScript to convert between different byte units.
JavaScript Byte Unit
In JavaScript, a byte is a basic data unit that represents the size of data stored in computer memory or hard disk. 1 byte is the data size of 8 bits (8 binary bits). All numbers, strings, and objects in JavaScript can be converted to bytes.
The following table lists some byte units used in JavaScript.
Unit | Memory size |
---|---|
1 | |
1024 | |
1024 * 1024 | |
1024 | 1024 1024 |
KB = 1024 * Byte
MB = 1024 * KB
GB = 1024 * MB
KB = Byte / 1024
MB = KB / 1024
GB = MB / 1024
function bytesToKB(bytes) { return bytes / 1024; } function bytesToMB(bytes) { return bytes / (1024 * 1024); } function bytesToGB(bytes) { return bytes / (1024 * 1024 * 1024); } function KBToBytes(kilobytes) { return kilobytes * 1024; } function MBToBytes(megabytes) { return megabytes * 1024 * 1024; } function GBToBytes(gigabytes) { return gigabytes * 1024 * 1024 * 1024; }
const fileSize = 2147483648; // 2 GB in bytes const fileSizeInKB = bytesToKB(fileSize); // 2097152 KB const fileSizeInMB = bytesToMB(fileSize); // 2048 MB const fileSizeInGB = bytesToGB(fileSize); // 2 GB const sizeInKB = 800; // 800 KB in bytes const sizeInMB = KBToMB(sizeInKB); // 0.78125 MB const sizeInGB = KBToGB(sizeInKB); // 7.62939453125e-4 GB const sizeInBytes = KBToBytes(sizeInKB); // 819200 bytes
The above is the detailed content of How to convert between different byte units in javascript. For more information, please follow other related articles on the PHP Chinese website!