J Mei J Mei - 1 year ago 110
C Question

Bitwise masking

Assuming an environment where

long int
is a 64-bit type, suppose I have an
long int = 0x0123456789ABCDEF
and I want to get the byte that represents 89. Would this line work?

n = (n >> (b << 3)) & 0xFF;

where n is the
long int
and b is the byte I want. So
would be 3 and shifting it left 3 would multiply it by 8 changing it into a byte so shifting should look like this 0x0123456789. Is using & 0xFF the right way to mask to get the last byte?

Answer Source

Yes, this is the correct approach. This online example on ideone.com prints 89 as expected.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download