ssubbarayan <> wrote:
> I developed the following program:
> void parsebytes(unsigned char* data);
> struct info
> {
> unsigned char day;
> unsigned char month;
> short year;
> };
> struct info info1;
> struct info info2;
> int
> main(int argc, char *argv[])
> {
> info1.day=12;
> info1.month=8;
> info1.year=2007;
> parsebytes((unsigned char*)&info1);
> system("PAUSE");
> return EXIT_SUCCESS;
> }
> void parsebytes(unsigned char* data)
> {
> printf("day is %d\n", data[0]);
> printf("month is %d\n", data[1]);
> printf("year is %d\n", ((data[2] <<
| data[3]));
> }
> The above program gives proper value of 12,8 for day and month.But
> year value I always get junk.What should be done to correct this and
> where have I gone wrong?
There are at least two aspects that lead to problems. First
of all you can't assume that the members of a structure are
all following each other directly without any "spacing" in
between. A compiler is allowed to put as many "padding bytes"
as it want's between the members of a structure. This normally
happens due to alignement issues - some types of variables
can't start at arbitrary addresses and the compiler must make
sure that those members start at allowed addresses.
The second problem is that you make some assumptions about
the way a short int is stored in memory which might be wrong.
You assume that a short int only consists of two bytes and that
the most-significant byte is stored at a lower address than the
least-significant byte. Both assumptions can be correct on your
machine but they don't are generally correct. While a short int
requires at least two 8-bit bytes (but there are also machines
with more bits in a byte, e.g. 16 bits, so a short int may be
stored in a single byte) it can be longer. And the assumption
about the ordering of the two bytes is, assuming that two 8-bit
bytes are used, only true on big-endian machines, on many (low-
endian) machines the least-significant byte is stored at the
lower address.
Regards, Jens
--
\ Jens Thoms Toerring ___
\__________________________
http://toerring.de