2

I am new in C. And I wonder can I create a variable with only one bit in the c programming language? or a variable with three bits.

For example :

variable_type var1=0; /* 1 bit */

printf("%d",sizeof(var1)); /* output= 0.125 */

variable_type var2=5;  /* 3 bit ,binary= 101 */

printf("%d",sizeof(var2)); /* output=0.375 */

The "sizeof()" notation above is probably wrong. I did something like this to explain myself.And I assume you know. 1 byte = 8 bits.

Thanks.

  • 3
    No. The minimum bit-size of an object is `CHAR_BIT` bits (usually `8`, can be more). Of those you can use only `1` bit though. `struct OneBit { unsigned int single: 1; }; struct OneBit x; x.single = 0; x.single++;` – pmg Apr 10 '21 at 12:15
  • 1
    You can create a bit field, but it is always contained in at least 8 bits, as pmg says. – Paul Ogilvie Apr 10 '21 at 12:17
  • 1 byte is *at least* 8 bits wide, but C allows for wider bytes. There have been real-world systems with 9-bit bytes, for example. – John Bode Apr 10 '21 at 12:49
  • Why do you need this? – user14063792468 Apr 10 '21 at 13:00

1 Answers1

4

Can I create a variable with only one bit in the c programming language?

No.

Objects are positive multiples of CHAR_BIT bits wide. CHAR_BIT is at least 8 bits. (Uncommon implementations have CHAR_BIT > 8.)

An struct object can have bit fields. Below, the member bt is 1 bit, yet struct one_bit is more bits due to padding in meeting the above requirement.

struct one_bit {
  unsigned bt:1;
}

Note:

_Bool acts as if it had only one value bit, but like any other object, _Bools cannot be smaller than CHAR_BIT bits. @John Bollinger

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256