How can I safely convert an integer to a bit field in the context of bitwise or?

Earlier, I asked this question and received an answer that worked on an example that I provided, but does not seem to generalize to bitwise OR. Here is an example from this question, but with the addition of bitwise OR.

#include <stdint.h>

struct MaskAndCount{
    uint64_t occupied : 56;
    uint8_t numOccupied : 8;
};

int main(){
    int count = 7;
    MaskAndCount foo;
    foo.occupied &= ~(1L << count) & 0x00FFFFFFFFFFFFFF;
    foo.occupied |= (1L << count) & 0x00FFFFFFFFFFFFFF;
}

Now, when we compile, we do not get a warning from the first line, but we get a warning from the second line.

g++ -Wconversion Main.cc
Main.cc: In function ‘int main()’:
Main.cc:12:18: warning: conversion to ‘long unsigned int:56’ fromlong unsigned int’ may alter its value [-Wconversion]
     foo.occupied |= (1L << count) & 0x00FFFFFFFFFFFFFF;

Again, I would pose the same two questions.

  • Will a written conversion have the desired effect of trimming the most significant bits of the value to the right?
  • Is there a way to either disable the warning locally, or express the same behavior with a different syntax that does not trigger the warning?
+2

Source: https://habr.com/ru/post/1656854/


All Articles