C++ Conversion Error when Accessing Bits to Set a Bit Field

  Kiến thức lập trình

We are using bitfields to represent elements of a register read from a device.

// defined
struct Register{
  uint8_t field : 1;
};

// later
uint8_t byte{0}; // read from 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/ToM191e4q

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT