In article <46***********************@news.free.fr>
Charlie Gordon <ne**@chqrlie.orgwrote:
>You SHOULD use a function for this, possibly an inline function.
Indeed, in some cases it turns out to be faster to call a regular
(non-inline) function than to do the code in line (either with a
macro, or with an inline function). (As always, the way to find
out is to measure it. If you do a lot of these conversions, it
may be worth looking at your compiler's output. Many of today's
ILP32-LL64 compilers produce poor 64-bit shift-and-mask code, so
this sort of micro-optimization is occasionally worthwhile.)
>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]);
}
I find that applications that do this tend also to do 16 and/or
32-bit numbers, so for the second case, consider, e.g.:
static inline uint32_t read32(const unsigned char *b) {
return ((uint32_t)b[0] << 24) | ((uint32_t)b[1] << 16) |
((unsigned)b[2] << 8) | b[3];
}
static inline uint64_t read64(const unsigned char *b) {
return ((uint64_t)read32(b) << 32) | read32(b + 4);
}
One might also consider also using "unsigned long" and "unsigned
long long" instead of the (possibly overspecified) uint32_t and
uint64_t aliases; and read32 can call read16() twice, and read16()
can use plain "unsigned int" (as the code in read32 above shows).
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it
http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.