Pages: [1]   Go Down
Author Topic: pointers - casting - what does this mean?  (Read 302 times)
0 Members and 1 Guest are viewing this topic.
ottawa, canada
Offline Offline
God Member
*****
Karma: 5
Posts: 989
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I came across the following in the library for an ethernet module.  It's to do with calculating a checksum. 

I THINK it means: take the two bytes at the adrress in ptr as a 16 bit unsigned int and add them to the 32 bit signed integer sum but all the casting leaves me a bit boggled.

Code:
char * ptr;
long sum;
...
sum += (unsigned int) (((unsigned long)*ptr<<8)|*(ptr+1));

Is it somehow different from sum += *(unsigned int*)ptr; Which is plenty ugly enough already.
Logged

Offline Offline
Edison Member
*
Karma: 18
Posts: 1170
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Well, your are missing the |* part.

It is taking two 8 bit quantities (*ptr and *(ptr+1) and combining them into 1 16 bit number (*ptr is the MSB) and adding that to sum, so your equivalent is not even close.
Logged

Global Moderator
Dallas
Offline Offline
Shannon Member
*****
Karma: 176
Posts: 12283
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Is it somehow different from sum += *(unsigned int*)ptr; Which is plenty ugly enough already.

Not much different.  The intent is to ensure the byte ordering.  With your expression, the byte ordering depends on the compiler / architecture.  With the other expression, the byte order is always the same (presumably "network order").

The (unsigned long) cast is strange.  Seems rather pointless given the facts that the value can never exceed 16 bits and it is followed by the (unsigned int) cast.  Oh well.
Logged

ottawa, canada
Offline Offline
God Member
*****
Karma: 5
Posts: 989
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Is it somehow different from sum += *(unsigned int*)ptr; Which is plenty ugly enough already.

Not much different.  The intent is to ensure the byte ordering.  With your expression, the byte ordering depends on the compiler / architecture.  With the other expression, the byte order is always the same (presumably "network order").

The (unsigned long) cast is strange.  Seems rather pointless given the facts that the value can never exceed 16 bits and it is followed by the (unsigned int) cast.  Oh well.

ah, I get it.  excellent point.
Logged

Pages: [1]   Go Up
Jump to: