Re: Require Help in Parsing strings!!!



On 2006-03-27, None <vedanarayanan.ganesan@xxxxxxxxx> wrote:
You can use the power of union and combinate with struct to disect the
stream of bytes into organized data of your class. For eg your struct

[...]

typedef struct __ns_rr {
char name[NS_MAXDNAME];
uint16_t type;
uint16_t rr_class;
uint32_t ttl;
uint16_t rdlength;

union
{
const uchar_t rdata[MAX_BYTES_POSSBL_IN_ANY_DATA];

struct NAPTR
{
unsigned int order;
unsigned int preference;
char flags[SOME_SIZE1];
char services[SOME_SIZE2];
char regexp[SOME_SIZE3];
char replacement[SOME_SIZE4];
};

struct Another_NAPTR
{

};

} any_one_data;

and so on...
} ns_rr;

Use the 'type' field of '__ns_rr' to determine which field of the union
(that is any_one_data) has to accessed.

I think this is best way of organizing a stream of bytes and
interpreting it based on some type.
[...]

Not sure exactly what this is for, but if it involves writing a stream
of bytes into rdata and then reading it out of one of struct NAPTR etc.
(don't they need names anyway?) don't forget about structure padding--
you can't make any assumptions about how the bytes in rdata and the data
in the structs match up apart from for the first member of each struct.

See http://www.c-faq.com/struct/io.html and
http://www.c-faq.com/struct/padding.html.

Also, better style not to start identifiers with underscores (these are
"reserved").

In general though unions like this are a good way of reinterpreting data
where that's necessary.
.



Relevant Pages

  • Re: Memory layout in unions
    ... If I have a union with an anonymous struct, ... unsigned int ccount; ... Standard C does not allow anonymous struct members. ...
    (comp.lang.c)
  • [PATCH] netfilter endian regressions
    ... struct xt_connlimit_info { ... unsigned int limit, inverse; ... union nf_conntrack_man_proto ... static inline bool already_closed ...
    (Linux-Kernel)
  • Re: offset macro for bit fields
    ... struct speed_part ... unsigned int left_wheel:4; ... It is not a good idea to combine these into a union. ... the association can change between compiler on the same platform, ...
    (comp.lang.c)
  • Re: Linux 2.6.27.21
    ... # disable pointer signed / unsigned warnings in gcc 4.0 ... struct dm_crypt_request { ... itd_init (ehci, stream, itd); ... iso_stream_put; ...
    (Linux-Kernel)
  • Re: [patch 21/24] perfmon: Intel architectural PMU support (x86)
    ... +struct pmu_eax { ... unsigned int num_counters:8; ... I need more than eax. ... We could rewrite this union to include ...
    (Linux-Kernel)