Hi I want to declare a 12 bit variable in C or any "unconventional" size variable (a variable that is not in the order of 2^n). how would I do that. I looked everywhere and I couldn't find anything. If that is not possible how would you go about saving certain data in its own variable.
- 1This is a bit too broad. Could you specify what you are trying to achieve?Arc676– Arc6762016-01-18 02:02:36 +00:00Commented Jan 18, 2016 at 2:02
- One way is to declare a 16-bit variable and only use the lowest 12 bits.Stack Exchange Broke The Law– Stack Exchange Broke The Law2016-01-18 02:09:11 +00:00Commented Jan 18, 2016 at 2:09
- What do you actually try to accomplish, what is your deeper problem? That might be an XY-problem.too honest for this site– too honest for this site2016-01-18 02:50:49 +00:00Commented Jan 18, 2016 at 2:50
3 Answers
Unlike Ada, C has no way to specify types with a limited range of values. C relies on predefined types with implementation defined characteristics, but with certain guarantees:
Types
shortandintare guaranteed by the standard to hold at least 16 bits, you can use either one to hold your 12 bit values, signed or unsigned.Similarly, type
longis guaranteed to hold at least 32 bits and typelong longat least 64 bits. Choose the type that is large enough for your purpose.Types
int8_t,int16_t,int32_t,int64_tand their unsigned counterparts defined in<stdint.h>have more precise semantics but might not be available on all systems. Typesint_least8_t,int_least16_t,int_least32_tandint_least64_tare guaranteed to be available, as well as similarint_fastXX_ttypes, but they are not used very often, probably because the names are somewhat cumbersome.Finally, you can use bit-fields for any bit counts from
1to64, but these are only available as struct members. bit-fields of size one should be declared asunsigned.
5 Comments
intNleast_t and intNfast_t and their unsigned counterparts are guaranteed to be available.int, etc.=. But the older I get the more I think they might actually not that bad to be used if the guaranteed minimum range is sufficient. Of course, if you need a specific size, (u)intN_t are the logical choice.Data is always stored in groups of bytes (8 bits each).
In C, variables can be declared of 1 byte (a "char" or 8 bits), 2 bytes (a "short" int on many computers is 16 bits), and 4 bytes (a "long" int on many computers is 32 bits).
On a more advanced level, you are looking for "bitfields".
See this perhaps: bitfield discussion
6 Comments
char is the same a s byte, but - see 1 3) Integer types may include padding bits, thus in principle an int with 17 used bits is possible. It may or may not contain padding, this depends on the width of a byte/char..@<name>, otherwise your comment can get through unnoticed. About the text: What does please you? If you think I am wrong, provide a reference to the corresponding section in the standard.