1

I have an unsigned char array of size 256:

unsigned char test[256];

I want to reduce the size of the array such that there is only one bit consumed by each index, for example index 0 to 7 should consume 1 byte so i only need 256/8 bytes. Is it possible to do that in C?

user438383
  • 5,716
  • 8
  • 28
  • 43
Scarlet
  • 131
  • 7
  • 4
    It is not possible with C syntax. You can implement it with functions. – i486 Apr 13 '22 at 08:20
  • 5
    Scarlet, No. Instead use `unsigned char test[256/8];` and mask operations. – chux - Reinstate Monica Apr 13 '22 at 08:20
  • Why can't op use struct with 256 1-bit fields? – Allan Wind Apr 13 '22 at 08:31
  • 2
    @AllanWind You could have 256 1-bit fields, but you couldn't access them using array syntax. Each bitfield would be individually named. – user3386109 Apr 13 '22 at 08:38
  • 1
    Even compilers that support bit-sized data types as an extension don't allow arrays of bits, at least the ones I used. – the busybee Apr 13 '22 at 08:58
  • 3
    A footnote to §6.7.2.1 in the C11 Standard says: *The unary & (address-of) operator cannot be applied to a bit-field object; thus, there are no pointers to or arrays of bit-field objects.* – Adrian Mole Apr 13 '22 at 09:03
  • You would have to define your own functions to get, set, test (etc.) the appropriate bits of a 256/8 array. But the code for those functions would almost certainly take up more memory than the 224 bytes you would save. – Adrian Mole Apr 13 '22 at 09:11
  • The C++ Standards committee tried something like this over 10 years ago when specifying how a `std::vector` of `bool` should work. The complaints *still* haven't stopped. – Adrian Mole Apr 13 '22 at 09:13

0 Answers0