6

I require a 4 bit integer in a design for less memory use. In any version of c++ ,c++11 ,c++14 any can be used for the design.

Aman Gupta
  • 81
  • 1
  • 1
  • 6
  • Make a struct with a 4-bit bitfield – M.M Jun 12 '17 at 07:07
  • No there isn't such type. But you can always use `uint8_t` and bit masking and shifting. – πάντα ῥεῖ Jun 12 '17 at 07:07
  • 2
    The smallest integer type in C++ is `char` which is usually 8 bits. Are you targeting a memory-constrained embedded system? Otherwise it's more work to try these kind of micro-optimizations (it will also make the code harder to read, understand and maintain). It might also be a bit of premature optimization. Please try to elaborate on *why* you want to use "less memory" in a way that will probably use more CPU cycles instead. – Some programmer dude Jun 12 '17 at 07:08
  • 1
    If you are genuinely interested in this topic, check out: CppCon 2016: Chandler Carruth “High Performance Code 201: Hybrid Data Structures" – keith Jun 12 '17 at 08:06

2 Answers2

7

There is no native 4bit datatype. But you could use an 8bit one to hold two 4bit values in the high/low nibble.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
4

no, but you can use:

struct A {
   unsigned int value1 : 4;
   unsigned int value2 : 4;
};
kain64b
  • 2,258
  • 2
  • 15
  • 27