Re: Variable declaration followed by colon?



On Apr 12, 12:11 pm, Antoninus Twink <nos...@xxxxxxxxxxxxxx> wrote:
On 12 Apr 2008 at 15:17, Yunzhong wrote:

What does this represent?
unsigned int n   : 6;

Inside a structure or union, it represents an unsigned integral
bitfield that occupies 6 bits;

Perhaps the OP will wonder why such a thing could be useful.

A couple of common examples where bitfields are used are device drivers,
because combinations of flags (i.e. bits) are often stored in a single
byte in hardware; and binary data formats, which frequently contain
fields that aren't aligned at byte boundaries. Whether you realize it or
not, you're relying on bitfields every time you send an IP packet!
Here's the IP header struct that's used in every packet:

struct iphdr {
  unsigned int version:4;
  unsigned int ihl:4;
  u_int8_t tos;
  u_int16_t tot_len;
  u_int16_t id;
  u_int16_t frag_off;
  u_int8_t ttl;
  u_int8_t protocol;
  u_int16_t check;
  u_int32_t saddr;
  u_int32_t daddr;



};


Even assuming reasonable definitions for those types...

You realize, of course, that the structure you've described will not
work on any x86 machine (nor any other little endian machine), and is
dependant on the order in which bit fields are stored (again wrong for
most x86 implementations), and assumes you can actually used bit
fields on an unsigned char (assuming one makes the obvious correction
to your code) on the implementation in question.

So almost assuredly, the OP is *not* sending IP packets via such a
structure.
.



Relevant Pages

  • Re: How to use bitfields?
    ... difference with other integer types beside their bit size. ... It's just for readability that bitfields are used. ... struct ARGB1555 { ... unsigned int green: 5; ...
    (comp.lang.c)
  • Re: How to use bitfields?
    ... It's just for readability that bitfields are used. ... struct ARGB1555 { ... unsigned int green: 5; ... for the same target, ...
    (comp.lang.c)
  • Re: Variable declaration followed by colon?
    ... A couple of common examples where bitfields are used are device drivers, ... you're relying on bitfields every time you send an IP packet! ... Here's the IP header struct that's used in every packet: ... unsigned int version:4; ...
    (comp.lang.c)
  • Re: How to use bitfields?
    ... It's just for readability that bitfields are used. ... struct ARGB1555 { ... unsigned int green: 5; ... I don't use C because of its portability, but because it is the only language that allow me to do pseudo-assembly low-level code very tied to the hardware in such a way that I don't have to rewrite everything for each target. ...
    (comp.lang.c)
  • (Resend of 23/70 plus reply [PATCH 00/70] tty updates proposed for 2.6.27)
    ... So rework the entire API to pass the tty struct. ... const unsigned char *source, int count) ... unsigned int set, unsigned int clear) ...
    (Linux-Kernel)