c++embeddedbit-manipulation

Conversion error when accessing bits to set a bit field


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


Solution

  • It's indeed odd that you are getting 1 warning instead of 2 or 0.

    Particularly suspicious wording conversion from 'unsigned char', because your (byte >> 7) & 0x1 has type int.

    But since you're asking how to remove the warning, cast the value to a bool.

    r.field = ((byte >> 7) & 0x1) != 0; // access bit 7
    

    or

    r.field = bool((byte >> 7) & 0x1); // access bit 7