Torrius
Torrius

Reputation: 787

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)
{ ... }

Upvotes: 11

Views: 11962

Answers (5)

idij
idij

Reputation: 770

If you mean programming domain traditional kilo = 1024, then no.

If you mean SI unit standard kilo = 1000, then you can (a bit awkardly) use some that are defined in the C++ ratio header.

#include <ratio>
constexpr auto two_kilo = std::kilo::num * 2;

I guess strictly you should account for both the numerator std::kilo::num and the denominator std::kilo::den, but absent a complete overhaul of scientific terminology, the denominator is going to be 1 for std::deca up, whereas the numerator will be 1 for std::deci down

Upvotes: 2

Iain Ballard
Iain Ballard

Reputation: 4818

Not that it adds much, but I quite like this form:

#define KILOBYTES * 1024UL
#define MEGABYTES * 1048576
#define GIGABYTES * 1073741824UL

Which you can use like

    if (size > 10 MEGABYTES) { ...

Upvotes: 1

You
You

Reputation: 23774

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;

Upvotes: 18

unwind
unwind

Reputation: 399813

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)

Upvotes: 21

masoud
masoud

Reputation: 56479

There is not. But why you don't make them by your own :

const unsigned long BYTE     = 1;
const unsigned long KILOBYTE = 1024;
const unsigned long MEGABYTE = 1024 * 1024;
const unsigned long GIGABYTE = 1024 * 1024 * 1024;

and also

const unsigned long long TERABYTE = 1024ULL * 1024 * 1024 *1024;

Read more...

Upvotes: 2

Related Questions