Introduction
Developers are familiar with terms such as kilobytes, megabytes and gigabytes. Most of us know that a kilobyte is approximately a thousand bytes and a megabyte is approximately a million bytes. That knowledge is sufficient for most purposes. This short article provides the information you'll need to be more precise.
Why Isn't a Kilobyte 1,000 Bytes?
A kilobyte is exactly 1,024 bytes. So why 1,024 bytes instead of a nice round number like 1,000 bytes? Since computers store all numbers in binary format, their limits can be expressed in values that are a power of two. So these terms are used to define "round" power-of-two numbers. 1,000 is not a power-of-two number, but 1,024 is.
And just as a million is a thousand times a thousand, a megabyte is a kilobyte times a kilobyte. So a megabyte is exactly 1,048,576 bytes, a power-of-two number that is approximately a million.
Here are some other power-of-two numbers.
Number |
Abbreviation |
Value |
1 Kilobyte |
KB |
1,024 Bytes |
1 Megabyte |
MB |
1,048,576 Bytes |
1 Gigabyte |
GB |
1,073,741,824 Bytes |
1 Terabyte |
TB |
1,099,511,627,776 Bytes |
1 Petabyte |
PB |
1,125,899,906,842,624 Bytes |
1 Exabyte |
EB |
1,152,921,504,606,846,976 Bytes |
Defining Values in Code
I was working on an MFC application recently that needed to work with these large power-of-two numbers. So I ended up defining C++ macros for them. Maybe someone else will find them useful so I've included them in Listing 1.
Listing 1: C++ Macros for Declaring Power-of-Two Numbers
#define KB(n) (((UINT64)0x400)*((UINT64)(n)))
#define MB(n) (((UINT64)0x100000)*((UINT64)(n)))
#define GB(n) (((UINT64)0x40000000)*((UINT64)(n)))
#define TB(n) (((UINT64)0x10000000000)*((UINT64)(n)))
#define PB(n) (((UINT64)0x4000000000000)*((UINT64)(n)))
#define EB(n) (((UINT64)0x1000000000000000)*((UINT64)(n)))
These macros make it easy to declare large power-of-two numbers. They each take a numeric argument and return that number times the corresponding value. For example, MB(5) returns five gigabytes, or 5,242,880.
Nothing complicated there. But if you need to declare these values, these macros should save you some time.
End-User License
Use of this article and any related source code or other files is governed
by the terms and conditions of
.
Author Information
Jonathan Wood
I'm a software/website developer working out of the greater Salt Lake City area in Utah. I've developed many websites including Black Belt Coder, Insider Articles, and others.