It is conventional and sane to use |
but +
works when everything is unsigned and the numbers to be added have disjoint ranges of bits. If the ranges of bits overlapped, then addition and logical or are not equivalent.
Out of curiosity I was wondering how these functions are implemented when the integer is negative for example.
The way I'd probably implement the macro is:
#define get32(buf) ((((buf)[0] & 0xFF) << 24) | \
(((buf)[1] & 0xFF) << 16) | \
(((buf)[2] & 0xFF) << 8) | \
(((buf)[3] & 0xFF) << 0))
The main difference is that the lines are more systematic; the optimizer will eliminate the << 0
operation (probably even if the -O
flag is not used). This will handle negative numbers OK in practice (numbers where the high bit of buf[0]
is set).