2 bytes to 12 bits via bitwise operators

30 Oct 2012

Hi all,..

writing a library for an I2C 12 bit ADC, and I'm not *very* familiar with bitwise operators. I now understand the following code, (Internet tutorials via google)

    //convert to 12 bit.
    int _12_bit_var; // 2 bytes
    char _4_bit_MSnibble = data[0]; // 1 byte, example 0000 1000
    char _8_bit_LSByte = data[1];   // 1 byte, example 1111 0000
    _12_bit_var = ((0x0F & _4_bit_MSnibble) << 8) | _8_bit_LSByte;   //example 100011110000

but what I don't understand is if there is any reason for the "&" with the 0x0F ?? It seems to me it's redundant, but I just picked it up out of a C++ tutorial.

I'm reasonably sure it'll work without it, am I missing something ?

31 Oct 2012

Hi, because you only need the 4 least significant bits of data[0]if you use "0x0F & " you delete the most significant 4 bits . if bit 8 of the byte[0] was one without "0x0F & " at the end of the conversion would have a negative number. if you are sure that in the most significant 4 bits there aren't nothing, you can not even use "0x0F & ".

31 Oct 2012

Brilliant, thankyou ! that makes total sense. Even though the 4 most significant bits are always meant to come back as '0000'. I shall leave that in as good coding practise. thanks again.