0

I'm trying to understand this cpp code so I can convert it to Java. r1 is an unsigned int bit field but it looks like here it is being set to a boolean value?

union GpioPins {
    struct {
      unsigned int ignoredPins1:2;
      unsigned int r1:1;
      unsigned int g1:1;
      unsigned int b1:1;
    } bits;
    uint32_t raw;
    GpioPins() : raw(0) {}
  };

then later on a loop containing

 GpioPins *bits = ...
 uint8_t red   = 141; // any number between 0..255
 uint8_t mask = 1 << i; // i is between 0..7 

 bits->bits.r1 = (red & mask) == mask;

The line that is confusing is the final one. Doesn't (red & mask) == mask resolve to true or false?

i.e. in Java this should look like:

 private static class GpioPins {

    static class Pins {
        int ignoredPins1;
        int r1;
        int g1;
        int b1; 
    }

    int raw = 0;
    Pins bits;
}

then later

GpioPins bits = ...
int red   = 141; // any number between 0..255
int mask = 1 << i; // i is between 0..7 

bits.bits.r1 = (red & mask) == mask;  // compile error, incompatible types

There is clearly something I don't understand in the cpp code, but don't know what it is to google it :-)

Blundell
  • 75,855
  • 30
  • 208
  • 233

2 Answers2

3

Assigning a bool to an unsigned int is a legal thing to do in C++. A true will set it to 1, and a false will set it to 0. This is done implicitly in C++.

In Java, the line: bits.bits.r1 = (red & mask) == mask; will not work because you cannot implicitly assign a boolean to an int.

Try this: bits.bits.r1 = ((red & mask) == mask) ? 1 : 0;

Tony Val
  • 362
  • 2
  • 5
  • 1
    The standard states that the implicit conversion of a `bool` to an `int` will yield `1` (if it holds `true`) (see the [reference page](http://en.cppreference.com/w/cpp/language/implicit_conversion)) - so it's not "usually" but always – UnholySheep May 03 '17 at 18:38
  • 1
    Welcome, Tony. Seen a few of your answers today. Keep it up! – Lightness Races in Orbit May 03 '17 at 18:41
1

Doesn't (red & mask) == mask resolve to true or false?

Yes, it does!

Next, during the assignment to r1, your true or false is coerced into an unsigned int, with value 1 or 0 respectively. C++ has implicit conversions that make this happen.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055