Is there any datatypes with size less than a byte? (C++) | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 3

Is there any datatypes with size less than a byte? (C++)

Hello, I'm trying to create a number datatype, which uses boolean arrays like bits and works like a number and lacks some weaknesses of integers and floats. I'm not happy with booleans, because they require 1 byte for only 2 possibilities, is there any datatypes that require less than a byte of memory? I'm searching for a boolean like datatype which requires only 1 bit of memory. By default I would be changing booleans to signed shorts or even bytes, but they would be harder to handle than booleans.

4th Mar 2020, 8:12 AM
Seb TheS
Seb TheS - avatar
6 Respuestas
+ 4
You can't allocate anything less than a byte, the CPU does not have the ability to store only 1 bit without using up an entire byte. What it can do is store multiple bits at once so instead of using 1 boolean you'll have to use booleans in sets of 8.
4th Mar 2020, 8:44 AM
Dennis
Dennis - avatar
+ 2
C allows you to spilt integers into bit fields. A 32 bit int can be used as 8 x 4 bit numbers, or for your case 32 single bit numbers. C++ has bitset which is a container that behaves like an array of bits. This may be close to what you want already.
4th Mar 2020, 9:44 AM
Jared Bird
Jared Bird - avatar
+ 2
Jared Bird Could you give an example of bitset usage?
4th Mar 2020, 10:21 AM
Seb TheS
Seb TheS - avatar
4th Mar 2020, 10:29 AM
Fernando Pozzetti
Fernando Pozzetti - avatar
+ 2
Seb TheS The link from Fernando Pozzetti is quite informative. Just ask if you are not sure about anything.
5th Mar 2020, 7:30 AM
Jared Bird
Jared Bird - avatar
+ 2
std::vector<bool> is optimized to pack 8 values per byte. Also, keep in mind that if you add numbers one bit at a time that's going to be at least 8 times slower than adding them one byte at a time and at least 32 times slower than adding them one 32-bit int at a time.
5th Mar 2020, 7:23 PM
Vlad Serbu
Vlad Serbu - avatar