I have a C structure like this …
struct icmp_prefixopt {
u_int8_t icmpopt_type;
u_int8_t icmpopt_len;
u_int8_t prefixlen;
u_int8_t lflag:1;
u_int8_t aflag:1;
u_int8_t reserved:6;
};
and I have provided values to members like this in same module-
popt= (struct icmp_prefixopt *)
malloc(sizeof(struct icmp_prefixopt));
popt->icmpopt_type = 3;
popt->icmpopt_len = 4;
popt->prefixlen = (u_int8_t)strtoul(arg, (char **)NULL, 0);
arg = index(arg, '+');
if (arg) {
++arg;
popt->lflag = ((u_int8_t)strtoul(arg, (char **)NULL, 0))&1;
}
arg = index(arg, '+');
if (arg) {
++arg;
popt->aflag = ((u_int8_t)strtoul(arg, (char **)NULL, 0))&1;
}
arg = index(arg, '+');
if (arg) {
++arg;
popt->reserved = 32; //((u_int8_t)strtoul(arg, (char **)NULL, 0))<<2;
}
where arg is command line argument passed to this module.
Now looking at the contents of structure after execution in hex format ->
03 04 20 81
icmpopt_type: seems fine
icmpopt_len: seems fine
prefixlen: seems fine
but bits looks like reversed for other 3 fields in their constitute byte-
lflag:1; aflag:1; reserved:6
so it should have been – 10100000=A0 but actually they are =>81=10000001
It arise many questions to me …
-
Is there anything to do with little endian/big endian?
-
If yes, what is the counterpart for functions like htonl and htons for 8 bit.
-
If no, what may be the possible issue or have I misunderstood something completely ?
-
What is best approach ? To modify order of these fields within the structure
itself or applying some bit wise operator and shifting of bits here itself?
The input provided at command line-
32+1+0+32
This final 32 serves no purpose here,as I have fixed 32 in module itself for testing.
Although my actual purpose needs to consider this field also.
Please help me soon with any alternative approach.
Thanx in advance.
Edit:

This is the actual structure I need to create and along with creating, need to made a provision for users to specify values for all the fields through GUI. (Right now only through linux command line).
I guess I have made the problem more clear now but still if any further information is required, I would be much happy to add.
How the compiler chooses to pack bit-fields is completely implementation-dependent. It doesn’t necessarily have anything to do with endianness.
htnol(and similar) don’t apply to bit-fields. If you need a guaranteed order, then you will need to manually pack auint8_tyourself. For example:Of course, in practice, you should use sensible
#defines rather than magic numbers (for 6 and 7). And you may decide to wrap this in a bunch of setter and getter functions.