We are using bit fields to represent elements of a register read from a device.
#include <cstdint>
struct Register {
uint8_t field : 1;
};
int main() {
uint8_t byte{0}; // Read from a device
Register r;
r.field = (byte >> 5) & 0x1; // access bit 5
r.field = (byte >> 7) & 0x1; // access bit 7, warns
}
We are also using the flag -Werror=conversion
. For some reason, accessing bit 0 through 6 compiles without warning. However, accessing bit 7 warns for the conversion error: conversion from 'unsigned char' to 'unsigned char:1' may change value [-Werror=conversion]
.
Any ideas why this might be? Or how to right it in a way that will not warn of a conversion error?
Example here, https://godbolt.org/z/Ghd5ndnKd
-Wconversion
, it was always unreliable and prone to false positives. – Stemmabyte
is a wider type when you select a bit from it? – Performingint shift = 7; r.field = (byte >> shift) & 0x1;
compiles – Boilingr.field = ~byte & 128 ? 0 : 1;
compiles (it even gives the expected code) butr.field = byte & 128 ? 1 : 0;
does not... – Kilt