Search code examples
c++cmemorybit

Reading bits from the bin value


What is the order one has to read the bits from the bin value? Having for e.g. this official MS doc site regarding the lParam of the WM_CHAR message, they explain what bits have what meaning. Taking the bits 16-23 for the scan code value should I read the bits from right to left or vice versa?


Solution

  • The page you linked to uses LSB 0 bit numbering so you can extract bits 16-23 with

    lParam & 0b00000000111111110000000000000000U
    //         |       |      |               |
    // bit    31      23     16               0
    //        MSB                            LSB
    

    Note: The 0b prefix for binary numbers requires C++14. In C it's only available as an extension in some implementations.

    You may also want to shift down the result with

    (lParam & 0b00000000111111110000000000000000U) >> 16U
    

    or simpler

    (lParam >> 16U) & 0b11111111U //  or  (lParam >> 16U) & 0xFFU