3

First of all, is it possible to do that? If yes what am i doing wrong in the below declaration?

struct mybitfields
{
    uint8_t a : 4;
    uint16_t c : 12;
} test;
Gokul
  • 455
  • 6
  • 17
  • This sounds a bit contradictory to me. What are you trying to do exactly? Why do you need your 4-bit integer to be 16-bit wide? – Medinoc Apr 22 '13 at 21:25
  • 6
    What is the problem with the given code? – Arun Apr 22 '13 at 21:26
  • I have a solution to my problem, just wondering if this is possible at all or not? – Gokul Apr 22 '13 at 21:30
  • 1
    You asked two questions: Is it possible? Yes. What are you doing wrong? We have no idea without knowing what you're trying to achieve and why you think you're doing something wrong ... Arun asked the essential question, which you dismissed. – Jim Balter Apr 22 '13 at 21:59
  • @ArunSaha, JimBalter What i meant, was it syntactically correct? (oh and i didn't dismissed the question, google-ing to spell "syntactically" ;) ) – Gokul Apr 22 '13 at 22:08
  • What does your compiler say (with a suitably high warning level set)? For example: http://stackoverflow.com/questions/2280492/bit-fields-of-type-other-than-int – Clifford Apr 23 '13 at 18:02

2 Answers2

4

Although what you are doing is possible, it is not portable: C99 standard says that bit-field base type must be a _Bool, signed int, or unsigned int, allowing implementation-defined types to be used with bit-fields (C90 requires a signed on an unsigned intas bit-field's base type; no other types are allowed).

See this answer for references to appropriate chapters of the C99 and C90 standards.

If your goal is to define a struct of bit-fields of size that is smaller than an unsigned int, you would be better off using bit shifts for portability.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

Your code will be accepted by most compilers, but strictly speaking the base type of a bitfield must be a (signed / unsigned) int.

uint8_t is a typedef for unsigned char, and uint16_t is probably a typedef for unsigned short, and bitfields made from these types are non-conforming.

Praetorian
  • 106,671
  • 19
  • 240
  • 328