2

I wanna create a custom data type which uses 5 bits. Max value is 20 (10100) and min value is 0 (00000). I couldn't imagine how could I accomplish that. So I decided ask your helps...

And it should do arithmetics like:

note n = 15;
note x = 5;
std::cout << n + x << std::endl; //Should print 20
std::cout << n-x << std::endl; //Should print 10

Regards & thanks for your efforts!..

  • Types in C++ use an integer number of bytes. So having a type which consumes only 5 bits is not possible. What you can do is design a class which limits the values stored in it, but it will consumes at least one byte. – AProgrammer Nov 17 '19 at 14:37
  • 1
    You will have to write a lot of code, that implements a custom class with overloads for every mathematical operation that makes them work for your 5-bit value, and figure out what they should do in case of an overflow, as well as implementing any required conversion operators that makes the class work with the C++ library (like iostream). This cannot be fully explained in a short answer on stackoverflow.com. You will need to spend some quality time with your C++ book, on this one. – Sam Varshavchik Nov 17 '19 at 14:37
  • For a starting point see https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading/4421719#4421719. – AProgrammer Nov 17 '19 at 14:39
  • @AProgrammer I thought, I could use bitwise operations to manipulate and use the only 4 bits of data, for example, I've got a class which has `Health` (0-100, in binary it's 7 digits), assume that my `CPU` is `16 bit`, now 9 bits left, let's call 3 another digits as `Level`, and another 6 as `Damage`, I could get & change the data via basic `AND`, `OR`, `XOR` binary logical operations, right? Wouldn't be this super useful in some cases? :D –  Feb 01 '21 at 22:55
  • I wonder if this is an XY problem. What exactly are you trying to accomplish to save 3 bits? – Cedric Martens Dec 15 '22 at 02:46
  • @A.TahaBaki That sounds a lot like you are trying to implement a binary bit-packed data format (for a game, or something). – Casey Dec 15 '22 at 02:58
  • That said, it's been three years, did you ever figure it out? – Casey Dec 15 '22 at 03:00

0 Answers0