-1

Sorry to ask again... But I seem to struggle with binary... I stumbled upon the following line

 MGC_SSPBUF_REG = (GESTIC_I2C_ADDR << 1) | 1; // write Address to MGC3130

Beside the fact, that don`t know, why one would shift the address to the left in order to save it, I cannot get my head around that OR operation.

Having an address ORed with "1" will always result in 1111 1111, wouldn`t it?


I am programming a Microchip PIC18F14K50 in C. While checking a code written by another company I stumbled across the following line:

if(MGC_SSPCON2_REG & 0x1F) { // MSSP not idle
...
}

Now, MGC_SSPCON2_REG is implemented as follows

 #define MGC_SSPCON2_REG         SSPCON2

Where SSPCON is the 8bit MSSP Control register (in I2C MODE).

What I do not understand, is how this if-condition works. Is it true when all the bits of the 8bit binary numbers are set to 1? As far as I understand, the argument is the bit wise AND operation on the 8bit register and the binary number 0001 1111 (0x1F).

I hope that I provided enough code to understand the question. I didn`t want to go to much into detail about how the register works.

Thank you in advance for your help :)

user3554329
  • 111
  • 2
  • 11

2 Answers2

2

It will execute if any of the 5 least significant bits are set (because of the bitwise and with 0x1F.

Jonathan Olson
  • 1,166
  • 9
  • 19
0

Having an address ORed with "1" will always result in 1111 1111, wouldn`t it?

No, why should it be all 1s? If you OR the value 1 (which is 000000..0001) you only set the bits that are set in the ORed value, i.e only 1 least significant bit.

Whatever value xyzxyz your address GESTIC_I2C_ADDR might be, your result is xyzxyz1 afterwards.

There is no reason why all the other bits would be affected as well.


What I do not understand, is how this if-condition works. Is it true when all the bits of the 8bit binary numbers are set to 1?

Well, mathematically spaking: Yes. ;) But not "IF and ONLY IF" all 5 bits are set. It is also true if only one of the bits is set.

As far as I understand, the argument is the bit wise AND operation on the 8bit register and the binary number 0001 1111 (0x1F).

If you understand this, and you understand the word "bitwise", everything should be clear.

I wonder how you get to the question above if you already made it to understanding this meaning.

Gerhardh
  • 11,688
  • 4
  • 17
  • 39
  • "No, why should it be all 1s? If you OR the value 1 (which is 000000..0001) you only set the bits that are set in the ORed value, i.e only 1 least significant bit." Because I am stupid and thought 1 to be all ones and thus every single bit gets ORed with 1. Thank you very much for your help!!! – user3554329 Aug 02 '17 at 06:46
  • Please don't mix "unexperienced but willing to learn" and "being stupid". Even for wrong assumption there might be a plausible reason. – Gerhardh Aug 02 '17 at 07:25