Reputation: 1
I'm struggling to get my mind around using pointers and arrays. I need some simple assistance with methods and conventions. I did see some similar posts, but I'm afraid I'm still at the point where I need very literal examples.
I have an array of 32-bit numbers that represent word-aligned data in a UDP packet. I need to access this data as 16-bit numbers for calculating the header checksum, and as 8-bit numbers when stuffing data. I have a statically defined buffer that I pass to my routine as
alt_u16 calc_udp_header_chksum (alt_u32 hdr[])
{
....
}
Upvotes: 0
Views: 407
Reputation: 51229
Just cast from (alt_u32*)
to (alt_u16*)
.
But endianness (byte order) may affect the result. I don't know details about what byte order you have.
THE CODE
alt_u16 calc_udp_header_chksum (alt_u32 hdr[])
{
int i;
alt_u16 ans = 0;
for(i=0; i<correct_size; ++i) {
ans+=((alt_u16*)hdr)[i];
}
return ans;
}
Upvotes: 0
Reputation: 4487
Down casting is not a problem.
You only need to cast the pointer to the new type. For example :
alt_u16* hrd16 = (alt_u16*)hdr;
Upvotes: 0
Reputation: 613442
You can simply cast hdr
to be a alt_u16*
. Like this:
alt_u16* hrd_word_aligned = (alt_u16*)hdr;
And now you can use hrd_word_aligned[0]
for the first 16 bit value, hrd_word_aligned[1]
for the second, and so on.
Analagous code can be used for alt_u8*
.
It doesn't matter whether your function receives alt_u32 hdr[]
or alt_u32 *hdr
.
Upvotes: 1