Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 843
Panda Avatar asked Feb 26 '26 16:02

Panda


1 Answers

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
like image 64
Drew Dormann Avatar answered Mar 01 '26 11:03

Drew Dormann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!