This is a combined response to two postings. Note that it
is customary in newsgroup responses to put the responding
comments after the comments being responded to, not before.
It would help if you could follow that custom.
Thanks for reply.
So basically in these cases we could avoid masking at all ?
We are avoiding use of the '&' ("masking") operator. Whether
masking takes place in the underlying hardware, or the operation
is done by some other means, is not known in general. Nor is it
important in most cases.
If we have a variable foo with 'foo >= 0' (and width at least
16 in the last case), then
foo % 256 == (foo & 255)
foo / 256 == foo >> 8
foo % 65536 == (foo & 65535)
foo / 65536 == foo >> 16
These relationships hold in all (conforming) C implementations.
If 'foo' is of unsigned integer type, then its value is always
greater than or equal to zero, so these relationships always
hold for unsigned types (again assuming in the last case that
the type being operated on with >> is at least 16 bits wide).
If we combine the second and third lines, we get
foo / 256 % 65536 == (foo >> 8 & 65535)
Again this relationship always holds if foo >= 0.
But what if a specific architecture doesn't have modulo
instruction and should be replaced with several instruction
versus bitshift/mask that is easy ?
First it's important to understand what sort of difference we're
talking about. The two approaches yield the same results,
numerically speaking; the only potential difference is how
fast the resulting programs will run.
These days, most compilers will do a better job than people of
picking good (meaning fast, among other things) instruction
sequences, and compilers are more knowledgeable (and reliable) in
their understanding of the differences between different machine
architecures than people are. There /are/ cases where it's
important to identify particular instruction sequences for a
particular architectural target; /but/, nowadays it is extremely
rare for that to manifest at the level of writing C source code.
So unless you're in a very unusual situation, and know exactly
what you're doing and why, it's better to pick source code that
expresses what you're trying to do as simply and directly as it
can. So, rather than think about what operations the _machine_
can do, think about what _you_ are trying to accomplish in terms
of the values involved, and write code keeping that second thing
in mind instead of the first.
Does that all make sense?