Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a type in c++ that takes less than one byte of memory?

For my computation I only need to use 7-bit space so I am using a char type. However I wonder if it is possible to declare my own type that uses less than one byte of memory?

like image 699
ElConrado Avatar asked Apr 16 '15 19:04

ElConrado


3 Answers

Not really. Inside a struct, you can make use of bit fields. So if you know you'll need a certain, fixed amount of entries, this would be a way to save a few bits (but note that the struct will always be padded to at least the next whole amount of bytes). Also note that due to the fact that "normal" CPUs can't address amounts smaller than an octet/byte, the access to these bit field values might be slower because of the extra instructions the compiler has to generate to get/store a value "in the middle". So in order to save a few bits, you have to spend some CPU time.

The C++11 standard says in chapter 1.7 The C++ memory model (emphasis mine):

The fundamental storage unit in the C++ memory model is the byte. A byte is at least large enough to contain any member of the basic execution character set (2.3) and the eight-bit code units of the Unicode UTF-8 encoding form and is composed of a contiguous sequence of bits, the number of which is implementation- defined.

In other words: the smallest addressable unit in C++ is at least 8 bits wide.

Side-note: In case you're wondering: there are machines like DSPs that can only address units larger than 8 bits at a time; for such a machine, the compiler may define "byte" to be, for example, 16 bits wide.

like image 132
DarkDust Avatar answered Oct 19 '22 11:10

DarkDust


Even if you try to create a bitset with size 1, it will consume a byte. So it is not possible to create a type less than a byte in C++

#include <iostream>       // std::cout
#include <string>         // std::string
#include <bitset>         // std::bitset

int main ()
{
  std::bitset<1> foo;
  std::bitset<1> bar (1);
  std::bitset<1> baz (std::string("1"));

  std::cout << "foo: " << sizeof(foo) << '\n';
  std::cout << "bar: " << sizeof bar << '\n';
  std::cout << "baz: " << sizeof baz << '\n';

  return 0;
}
like image 6
Steephen Avatar answered Oct 19 '22 11:10

Steephen


byte is the minimal addressable unit and has the minimum size in C++ equal to 1. And the memory is allocated in bytes. Even an empty class has at least size not less than 1 byte.

like image 3
Vlad from Moscow Avatar answered Oct 19 '22 09:10

Vlad from Moscow