Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

shifting in bitmasks #38

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

manuel-simon
Copy link

@manuel-simon manuel-simon commented Aug 31, 2021

Hi,

I have some problems when bitmasks are used to get data out of packets.

The problem is that shifting a signed/negative number is compiler-dependent. Some compilers perform an arithmetic shift if the value is signed/negative. ~0 can be interpreted as negative since the first bit is set. Then the shift is performed, filling up with 1 bits.

Standard C99 §6.5.7 (e.g. here):

The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type
or if E1 has a signed type and a nonnegative value, the value of the result is the integral
part  of  the  quotient  of E1 / 2 E2. If E1 has  a  signed  type  and  a  negative  value,  the
resulting value is implementation-defined.

What we need in the masks are logical shifts. These are performed if the value is positive/unsigned. This should be ensured declaring the 0 as an unsigned literal.
~0 -> ~0U

…ted logically or arithmetically (filling with 1-bits, if the sign bit is 1). Therefore explicitly stated to handle the shift logically, using an unsigned integer value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant