Re: macro help
- From: "Charlie Gordon" <news@xxxxxxxxxxx>
- Date: Sun, 30 Sep 2007 14:01:27 +0200
<inftoconc@xxxxxxxxx> a écrit dans le message de news:
1191144396.861742.54850@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Hi all,
I wrote a macro to read 8 bytes from a byte stream. Am not
sure if it is working ok. Can anyone please point out if there looks
to be a problem!
#define READ64(b) ( (uint64_t(*b)) << 56) + ((uint64_t(*(b+1))) << 48)
+ ((uint64_t(*(b+2))) << 40) +((uint64_t(*(b+3))) << 32)+((uint64_t(*(b
+4))) << 24) + (( uint64_t(*(b+5))) << 16) + (( uint64_t(*(b+6))) <<
8) + ( *(b+7))
Here b is a pointer to an unsigned char.
The macro does not fit on a single line, you must use \ to ensure that the 4
lines get pasted together by the preprocessor.
Your casts to uint64_t are incorrect for C: use (uint64_t)x, not uint64_t(x)
You MUST use parentheses around b in the body of the macro in case b is not
a primary expression.
This macro evaluates its argument multiple times, it MUST not be used with
an argument that has side-effects.
You SHOULD use a function for this, possibly an inline function.
You should document that it fetches a 64 bit value from the octet stream in
big endian order.
fixed macro:
#define READ64(b) (((uint64_t)(b)[0] << 56) | \
((uint64_t)(b)[1] << 48) | \
((uint64_t)(b)[2] << 40) | \
((uint64_t)(b)[3] << 32) | \
((uint64_t)(b)[4] << 24) | \
((uint64_t)(b)[5] << 16) | \
((uint64_t)(b)[6] << 8) | \
((uint64_t)(b)[7] << 0))
Function:
static inline uint64_t read64(unsigned char const *b) {
return ((uint64_t)b[0] << 56) | ((uint64_t)b[1] << 48) |
((uint64_t)b[2] << 40) | ((uint64_t)b[3] << 32) |
((uint64_t)b[4] << 24) | ((uint64_t)b[5] << 16) |
((uint64_t)b[6] << 8) | ((uint64_t)b[7] << 0);
}
If your compiler is not too smart, this might be better:
static inline uint64_t read64(unsigned char const *b) {
return ((uint64_t)(((uint32_t)b[0] << 24) | ((uint32_t)b[1] << 16) |
((uint32_t)b[2] << 8) | b[3]) << 32) |
(((uint32_t)b[4] << 24) | ((uint32_t)b[5] << 16) |
((uint32_t)b[6] << 8) | b[7]);
}
--
Chqrlie.
.
- References:
- macro help
- From: inftoconc
- macro help
- Prev by Date: Re: Read compressed files and deal with byte swapping.
- Next by Date: Re: Compiling a C program through another C program
- Previous by thread: Re: macro help
- Next by thread: Re: macro help
- Index(es):
Relevant Pages
|