Go Down

### Topic: pointers - casting - what does this mean? (Read 650 times)previous topic - next topic

#### bill2009

##### Apr 24, 2013, 09:58 pm
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: [Select]
`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.

#### KeithRB

#1
##### Apr 24, 2013, 10:02 pm
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.

#2
##### Apr 24, 2013, 11:10 pm
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.

#### bill2009

#3
##### Apr 24, 2013, 11:14 pm

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.

Go Up

Please enter a valid email to subscribe