Search code examples
c++if-statementbinarybitset

C++ bitset with if statement


I was wondering if there is anyway to use specific range of bits with if statement. im using a fpga to send 8bits binary data over usb to pc. each transaction has 3x 8 bits packets. in each packet first four bits are generated by outside module and i want to send control data in the last four bits. => usb interface accepts data as integers and i've got bitset function to convert integers to 8bit binary. i want to use last four bits to use with if statements. is there any way i can do this?

thanks in advance


Solution

  • If you have an unsigned char as input:

    void foo(uint8_t x) {
      uint8_t top4    = x >> 4;  // moves top 4 bits down by 4 positions
      uint8_t bottom4 = x & 0x0f; // zeros out top 4 bits, leaving bottom 4
    }
    

    This will work with int, short, etc., types as well, but you would need to &-mask the top results too to strip away the unwanted high bits there.