How to get bit flag status from unsigned int?

Hello all,

the bit flags in the table below indicate which key is pressed on the controller. If the value below is set in logical AND operation with the key status, the corresponding key is held.

The value comes as unsigned int, but now I have no idea how to get out for example when the button A is pressed?

|Bit Flag | Button |
|0x00000001|Cross or A|
|0x00000002|Triangle or Y|
|0x00000004|Circle or B|
|0x00000008|Square or X|
|0x00000010|D-pad Left|
|0x00000020|D-pad Right|
|0x00000040|D-pad Up|
|0x00000080|D-pad Down|
|0x00000100|Options or Menu|
|0x00000200|L1 or LB|
|0x00000400|R1 or RB|
|0x00000800|L2 or LT|
|0x00001000|R2 or RT|
|0x00002000|Left Stick Click|
|0x00004000|Right Stick Click|
|0x00008000|Right Stick Left|
|0x00010000|Right Stick Right|
|0x00020000|Right Stick Up|
|0x00040000|Right Stick Down|
|0x00080000|Special|

your masks seems to be using 32 bits. Are your unsigned int 32 bits as well ? (which platform are you using)

assuming it's a 32 bit value you would just mask and check against the mask

uint32_t value = ...; // whatever you got
const uint32_t crossOrA = 0x00000001ul;

if (value & crossOrA == crossOrA) {
  // Cross or A 
  ....
}

to handle all the possibilities, put them in an array and iterate over the array until you find a match.

You can drop the == crossOrA part if you like.

Or use a switch statement.

 const uint32_t CrossOrA = 0x00000001;
 const uint32_t TriangleOrY = 0x00000002;
 const uint32_t CircleOrB = 0x00000004;
 const uint32_t SquareOrX = 0x00000008;
 const uint32_t D_padLeft = 0x00000010;
 const uint32_t D_padRight = 0x00000020;
 const uint32_t D_padUp = 0x00000040;
 const uint32_t D_padDown = 0x00000080;
 const uint32_t OptionsOrMenu = 0x00000100;
 const uint32_t L1orLB = 0x00000200;
 const uint32_t R1orRB = 0x00000400;
 const uint32_t L2orLT = 0x00000800;
 const uint32_t R2orRT = 0x00001000;
 const uint32_t LeftStickClick = 0x00002000;
 const uint32_t RightStickClick = 0x00004000;
 const uint32_t RightStickLeft = 0x00008000;
 const uint32_t RightStickRight = 0x00010000;
 const uint32_t RightStickUp = 0x00020000;
 const uint32_t RightStickDown = 0x00040000;
 const uint32_t Special = 0x00080000;
 
void setup() {
  // put your setup code here, to run once:

}

void loop() {
     uint32_t value;


    // read input value
  //  value = whatever;  

    switch (value){
      case CrossOrA:
         // something
         break;
      case TriangleOrY:
        // something
        break;

// other possibilities ...
// and finally ...
 
      case Special:
        // something
        break;
      default:
        // error massage _ invalid input
      break;
    
    }
}

I wonder if there is a requirement to detect when 2 or more keys are pressed simultaneously ?

Yes if there is only one bit set at 1
(Which seems to be the case)

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.