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.
Asked
Active
Viewed 2.4k times
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
-
2The 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
-
1If 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 Answers
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
-
nibble is also used only in the struct. Is there any direct way to use the 4 bit int – Aman Gupta Jun 12 '17 at 07:25
-
3
4
no, but you can use:
struct A {
unsigned int value1 : 4;
unsigned int value2 : 4;
};

kain64b
- 2,258
- 2
- 15
- 27
-
1But the struct also use memory space ,so how much the total space is used in this case. – Aman Gupta Jun 12 '17 at 07:13
-
2@emlai That's unfortunately [not true](http://coliru.stacked-crooked.com/a/a5037c96e3494cf8). – πάντα ῥεῖ Jun 12 '17 at 07:20
-
3It would be true if you used `uint8_t` or `char` instead (assuming 8-bit char) – krzaq Jun 12 '17 at 07:21
-
Note that `sizeof(char)` always returns 1, so nothing can be smaller than a char - even is char is not 8 bits wide. – Richard Critten Jun 12 '17 at 07:34