so how do I do it? (was Re: call to revolt)

Peter da Silva peter at ficc.ferranti.com
Sat Jun 29 03:32:22 AEST 1991


In article <m0jspJY-0001ieC at shiva.reed.edu> minar at reed.edu writes:
> I'm writing some code right now that needs to extract information from a
> buffer that contains various types in it.

> Lets say that there's a chunk of memory that
> I *know* first contains a char, then an unsigned. I want to get these values.

Option 1: define a structure for the buffer. This will automatically handle
alignment requirements and the like.

Option 2: If the buffer is packed, or imported, you will have to step
through it byte by byte:

	char *bufp;
	unsigned u;
	char c;

	bufp = buffer;

	c = *bufp++;
	u = *bufp++ << bitsperchar;
	u |= *bufp++;

Or, if the buffer is little-endian:

	c = *bufp++;
	u = *bufo++;
	u |= *bufp++ << bitsperchar;

> this is nonportable, as to my understanding, as struct arrangements are not
> guaranteed.

No, that's portable. Structs are guaranteed to be in increasing order. Padding
is undefined, as is byte order within a word.

> while I'm at it, how do you get the offset of an element of a structure
> the ANSI way?

Use the offsetof() macro.
-- 
Peter da Silva; Ferranti International Controls Corporation; +1 713 274 5180;
Sugar Land, TX  77487-5012;         `-_-' "Have you hugged your wolf, today?"



More information about the Comp.std.c mailing list