Help with data casting

  • Thread starter Thread starter ampeloso
  • Start date Start date
A

ampeloso

Hello,
I have the following function:
WORD calcChecksum(BYTE data[], WORD length)
| /* Calculates a checksum of "data".
| */
| {
| WORD* i_data;
| WORD checksum= 0;
| BYTE i= 0;
|
| i_data= (WORD*)data;
|
| for (i= 0; i < length/2; i++)
| {
| checksum^= i_data; /* xor-ing */
| }
| return(checksum ^ 0xffff); /* inverting */
| }
| return (ushort)(checksum ^ 0xffff);
|
|
|
| }

When I get to i_data= (WORD*)data; the i_data becomes 6272.
data, which is data[0] is 128.
Someone gave me this explanation:

Sure but with the cast you pretend that you are pointing to a WORD,
that
means that you take both data[0] AND data[1] and vove it to an WORD.
That
means if data[0] = 128 (0x80) and data[1] = 24 (0x18). the result
i_data
hold 0x8018 after the move (that's 6272 on intel achitectures).

Where does data[1] come in? this all happens before the "for" clause.
I could use an explanation.
Thanks
Mike
 
I have the following function:
WORD calcChecksum(BYTE data[], WORD length)
| /* Calculates a checksum of "data".
| */
| {
| WORD* i_data;
| WORD checksum= 0;
| BYTE i= 0;
|
| i_data= (WORD*)data;
|
| for (i= 0; i < length/2; i++)
| {
| checksum^= i_data; /* xor-ing */
| }
| return(checksum ^ 0xffff); /* inverting */
| }
| return (ushort)(checksum ^ 0xffff);
|
|
|
| }

When I get to i_data= (WORD*)data; the i_data becomes 6272.
data, which is data[0] is 128.
Someone gave me this explanation:

Sure but with the cast you pretend that you are pointing to a WORD,
that
means that you take both data[0] AND data[1] and vove it to an WORD.
That
means if data[0] = 128 (0x80) and data[1] = 24 (0x18). the result
i_data
hold 0x8018 after the move (that's 6272 on intel achitectures).

Where does data[1] come in? this all happens before the "for" clause.
I could use an explanation.


It is not that difficult.
The array is an array of bytes. data[0] and data[1] both have values.
i_data is a pointer that points to the beginning of the array.

however, i_data is of the type WORD*, meaning the compiler assumes that it
points to an integer of 2 bytes wide.
this means that the word it is pointing to, consists of data[0] and data[1].
When i changes to 1, i_data will point to the word that consists of data[2]
and data[3].

The netto effect of this is that the data array is treated as an array of
WORDs because the checksum algorithm is a 16 bit algorithm.

Note that there is an error in the algorithm though. If the number of bytes
is odd, the value of the last byte is not taken along in the calculation, so
any change to that byte is invisible.

--

Kind regards,
Bruno van Dooren
(e-mail address removed)
Remove only "_nos_pam"
 
Back
Top