Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Header with memory size definitions

Is there standard C/C++ header with definitions of byte, kilobyte, megabyte, ... ? I dont want to make own defines. It's dirty in my opinion.

Example:

if (size > MEGABYTE)
{ ... }
like image 853
Torrius Avatar asked Apr 16 '13 07:04

Torrius


2 Answers

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)
like image 182
unwind Avatar answered Oct 01 '22 19:10

unwind


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;
like image 36
You Avatar answered Oct 01 '22 19:10

You