1

I was wondering if it is possible to create a 23-bit user defined type in c++. I can create a 24-bit type just fine using 3 chars however I am trying to get one bit less. Any suggestions?

ghosting999
  • 101
  • 12
  • You can always use 3 chars (or even just a int32_t) to store your type in -- do you have requirements that make such an approach inadequate? If so, it would help if you explicitly stated those requirements. –  Apr 20 '15 at 17:22
  • Perhaps [`std::bitset`](http://en.cppreference.com/w/cpp/utility/bitset) is what you're looking for, but maybe it isn't. – chris Apr 20 '15 at 17:23
  • You issue is that the platform will store the bits in the most convenient unit it has. For example, if your platform is 7-bits, you will still need to use 28-bit or 4 units, because the platform can't store bits individually. – Thomas Matthews Apr 20 '15 at 17:25
  • 2
    You cannot create a type whose representation is exactly 23 bits in size. You *can* create a type whose representation is larger, but of which you use only 23 bits. – John Bollinger Apr 20 '15 at 17:25
  • It would be possible if you compiled for a system where `CHAR_BIT` is 23. – chris Apr 20 '15 at 17:30
  • What about if you used 23 bools? (the memory will still be padded for 32 or 64 bits) – Fantastic Mr Fox Apr 20 '15 at 17:31
  • @Ben - Cringe. I've seen people do this and get the infamous 1,000,000 size array of 32-bit bools before. Oh the wasted space :) – Michael Dorgan Apr 20 '15 at 17:39
  • @MichaelDorgan: `vector` is supposed to be implemented as a bit-vector under the covers. – jxh Apr 20 '15 at 17:47

1 Answers1

3

You can use a bit-field.

struct TwentyThreeBits {
    int x : 23;

    TwentryThreeBits & operator = (int y) {
        x = y;
        return *this;
    }
};

This allows you manipulate the member x as a 23 bit value. The actual size of the type is likely larger (likely sizeof(TwentyThreeBits) is at least sizeof(int)).

If you would like to represent many items that only occupy 23 bits, you could create an array of bits (either with vector<bool> or with bitset) and access the right multiple of 23 into that array to get to the "object".

jxh
  • 69,070
  • 8
  • 110
  • 193