I can define values of an integer of different sizes in C++ using: std::int8_t
, std::uint32_t
, etc. Is there a way to define an integer that uses, say 14 bits?
Asked
Active
Viewed 326 times
2

oconnor0
- 3,154
- 6
- 34
- 52
-
3`std::int16_t` can hold at least 14 bits. Why do you need it *not* to hold those two extra bits? – Keith Thompson Jun 22 '15 at 19:46
-
Is this what you are looking for? http://stackoverflow.com/questions/1490092/c-c-force-bit-field-order-and-alignment – Captain Giraffe Jun 22 '15 at 19:46
-
No, you can provide a class behaving as int14, only. – Jun 22 '15 at 19:49
-
@KeithThompson For compiling to specialized hardware that supports weird sizes. – oconnor0 Jun 22 '15 at 19:49
-
Possible duplicate of http://stackoverflow.com/questions/2679801/custom-byte-size – Marco A. Jun 22 '15 at 19:50
-
2["The integers of unusual size? I don't think they exist."](https://en.wikipedia.org/wiki/The_Princess_Bride) – Keith Thompson Jun 22 '15 at 19:50
-
@oconnor0 If you´re compiling for unusual HW, `int` will be already how it should be on the HW. Your task is not to write a different integer type, but to make sure your code works with different `int` – deviantfan Jun 22 '15 at 19:52
-
@deviantfan The hardware supports regular ints and weird ints. – oconnor0 Jun 22 '15 at 19:54
-
What hardware is it? – Captain Giraffe Jun 22 '15 at 19:55
-
This is at least the 4th time I see such questions this year.... – user3528438 Jun 22 '15 at 19:57
-
@oconnor0 That´s fine, but nonetheless it makes no sense to write some int-emulating classes if you really want that weird hardware int. – deviantfan Jun 22 '15 at 19:58
-
If some specialized hardware supports 14-bit integers, I'd expect a compiler for such hardware to support their use somehow. – Keith Thompson Jun 22 '15 at 20:00
3 Answers
3
Is bitfield what you are looking for? In this example y takes 14 bits It's the closest match I can think of
struct x
{
int y :14 ;
} ;

marom
- 5,064
- 10
- 14
-
1In C, a bit field of type `int` may be either signed or unsigned; it's implementation-defined. I don't know whether the same rule applies to C++. In any case, explicitly using `signed int` or `unsigned int` isn't a bad idea. – Keith Thompson Jun 22 '15 at 19:48
1
You can create a class that behaves exactly like std::uint14_t would behave if it existed. Since any values that don't fit with signed types invoke undefined behaviour, typedef std::int16_t int14_t is a perfectly fine.

gnasher729
- 51,477
- 5
- 75
- 98
-
1Not exactly, because `uintN_t` is defined as containing no padding bits, but this class would have to contain padding bits. – M.M Jun 22 '15 at 21:17
-