Header with memory size definitions
As other answers pointed out, there is not. A nice solution in C++11 is to use user-defined literals:
constexpr std::size_t operator""_kB(unsigned long long v) {
return 1024u * v;
}
std::size_t some_size = 15_kB;
No, there are no such standard definitions. Probably because the added value would be very small.
You often see things like:
#define KB(x) ((size_t) (x) << 10)
#define MB(x) ((size_t) (x) << 20)
This uses left-shifting to express the operation x * 210 which is the same as x * 1,024, and the same for 220 which is 1,024 * 1,024 i.e. 1,048,576. This "exploits" the fact the classic definitions of kilobyte, megabyte and so on use powers of two, in computing.
The cast to size_t
is good since these are sizes, and we want to have them readily usable as arguments to e.g. malloc()
.
Using the above, it becomes pretty practical to use these in code:
unsigned char big_buffer[MB(1)];
or if( statbuf.st_size >= KB(8) ) { printf("file is 8 KB (or larger)\n"); }
but you could of course just use them to make further defines:
#define MEGABYTE MB(1)