Question
C++ Conversion Error when Accessing Bits to Set a Bit Field
We are using bitfields 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