I can typedef char
to CHAR1
which is 8 bits.
But how can I make 3 bit variable as datatype?

- 3,011
- 2
- 14
- 33

- 1,540
- 4
- 17
- 34
-
2Why a three bit routine? Computers are happier with bytes – Ed Heal Jul 10 '15 at 11:22
-
3Sounds like a [X-Y problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What exactly are you trying to achieve? – Yu Hao Jul 10 '15 at 11:23
-
@EdHeal I want to use them as CoS (Class of Service), as they are 3 bits. – Ishmeet Jul 10 '15 at 11:23
-
If negative comments are coming, I am deleting this question. – Ishmeet Jul 10 '15 at 11:26
-
1You do not need to use all eight bits. – Ed Heal Jul 10 '15 at 11:27
-
3Side note : `char` is not always 8 bits. – Quentin Jul 10 '15 at 11:28
-
@Quentin - Granted - but in most cases it is – Ed Heal Jul 10 '15 at 11:30
-
@Quentin How is `char` not always 8 bits. Can you please describe? – Ishmeet Jul 10 '15 at 11:39
-
1@Ishmeet: There is already an SO question for that http://stackoverflow.com/questions/881894/is-char-guaranteed-to-be-exactly-8-bit-long – Jay Bosamiya Jul 10 '15 at 11:41
-
Some people like to hold onto the past. Some machines had 7 bits with the eight bit being parity. – Ed Heal Jul 10 '15 at 11:43
-
[10 or 12 bit field data type](http://stackoverflow.com/q/29529979/995714), [Which C datatype can represent a 40-bit binary number?](http://stackoverflow.com/q/9595225/995714) – phuclv Apr 01 '17 at 02:45
3 Answers
You might want to do something similar to the following:
struct
{
.
.
.
unsigned int fieldof3bits : 3;
.
.
.
} newdatatypename;
In this case, the fieldof3bits
takes up 3 bits in the structure (based upon how you define everything else, the size of structure might vary though).
This usage is something called a bit field.
From Wikipedia:
A bit field is a term used in computer programming to store multiple, logical, neighboring bits, where each of the sets of bits, and single bits can be addressed. A bit field is most commonly used to represent integral types of known, fixed bit-width.

- 3,011
- 2
- 14
- 33
-
1It's also one of the most obscure core-language features of C, so it's best employed when you really can't do without it. – Matteo Italia Jul 10 '15 at 11:37
-
In the case of certain protocols etc (which require specific sized fields), is probably the only proper use I can think of for it. – Jay Bosamiya Jul 10 '15 at 11:39
It seems you're asking for bitfields https://en.wikipedia.org/wiki/Bit_field Just be aware that for some cases it's can be safer just use char or unsigned char instead of bits (compiler specific, physical memory layout etc.)
Happy coding!

- 5,291
- 2
- 18
- 42
typedef struct {
int a:3;
}hello;
It is only possible when it is inside structure else it is not

- 1,171
- 7
- 14