-1

What's the best data type that can handle a sequence of digits [0:9] in c++ with the least possible waste in memory?

I think it may be something like that

typedef bitset<4> Digit;
vector<Digit> myVector;

but I think that each bitset<4> reserves a byte -the same as a char-, so it's not better than a normal string, is it?

Are there any better idea to handle something like that?

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
Muhammad Magdi
  • 150
  • 1
  • 10
  • What are you trying to do? As this is written I'm unable to figure that out. – Mgetz May 07 '18 at 17:25
  • 1
    Write a wrapper over `std::vector` to store two digits per byte maybe? But why do you need it? `std::vector` with one digit per byte sounds a lot more convenient.. – HolyBlackCat May 07 '18 at 17:25
  • I'm trying to implement a BigInt class, but I want to build it with the least possible waste, so I want to find something better than std::string. @Mgetz – Muhammad Magdi May 07 '18 at 17:28
  • 1
    to store in `the least possible waste in memory`, each digit will occupy 4 bit (one nibble) , you could use one char to store 2 digits. One in MSB nibble and another in LSB nibble. In this way worst possible case (odd number of digit ) your one nibble will be unoccupied. WARNING Doing this way the code will be less manageable. – Ratul Sharker May 07 '18 at 17:30
  • @HolyBlackCat I think it may be a good choice. – Muhammad Magdi May 07 '18 at 17:31
  • 4
    Anything that you use that's smaller than a byte is going to incur overhead for encoding/decoding, making any operations you perform on your numbers slower. I'm not sure it's worth the tradeoff. – beaker May 07 '18 at 17:31
  • Thanks guys I got it. But why the question got -1 :"( -I hope things won't get worse- – Muhammad Magdi May 07 '18 at 17:36
  • 1
    Why are you using decimal digits in your class? – Barmar May 07 '18 at 17:39

1 Answers1

3

To store a value from a set of 10, 4bits are required.

But on 4 bits, 16 values can be represented. That is a waste of 6/16 =37.5%.

So the best representation would minimize the amount of waste.

The best way is to store in binary, where all the combinations of bits are utilized.

Robert Andrzejuk
  • 5,076
  • 2
  • 22
  • 31