News:

Let's find out together what makes a PIC Tick!

Main Menu

Translating from C

Started by trastikata, Aug 16, 2022, 05:12 PM

Previous topic - Next topic

trastikata

Hello all,

I am translating something from C and for the love of God I can't figure the meaning of an "If" statement. This might be a dumb question, but can you advise on the meaning of this:

if( myVar & 4 )
... do something ...

I'd appreciate your help.

Thanks

Pepe

If bit 2 of myvar is 1 then


If myvar and 4 <> 0 then

                    Else
Endif

atomix

If (myvar and 4) != 0 then

trastikata

Quote from: Pepe on Aug 16, 2022, 05:32 PMIf myvar and 4 <> 0 then

Thanks Pepe and atomix.

Thus if the relational operator (=<>) in an "If" statement is missing, then it means not equal to zero?

That's why I never liked C enough to learn it properly  ;D

top204

#4
As has been shown, the expression is masking all but bit-2 of "myvar" with binary value 00000100, then seeing if it is set and not giving a value of 0. If it is set, the value returned from the masking will be 4.

So the best, and most efficient, method in Positron is:

If MyVar.2 = 1 Then

ANSI C is a good language, but it does not support bit variables directly because when it was designed back in the mid to late 1970s, the microprocessors did not have any bit handling mnemonics. So it uses masking with And  for clearing and testing bits, and Or  for setting bits, which sometimes requires Anding before Oring, to clear bits first. And a multitude of confusing shifts for altering values to act as a mask for altering or testing. :-)

Some of the more recent alterations of C for microcontrollers do have real bit handling mechanisms built in to them, but they are not common and sometimes it looks like the code is using bits, but in the assembler code, it is still using masks, so is less efficient. And with C, there is a vast amount of copy and paste, so the code copied from something created for a microcprocessor is very inefficient on a microcontroller, and much more bloated than it should be. Therefore, slower to operate as well.

keytapper

Yeah, bit  handling is a dreadful case. Most of the libraries don't want to be MCU oriented otherwise they may fail to be usable for a broad number of MCU. Wiring is the leader :D
The if() case is by AFAIK  defaulting that anything non zero is TRUE,  whereas the resulting test is zero will skip the following instructions,  whichever enclosed by braces parenthesis or just one statement.
I use to get some translation and there are usually a bunch of function calls that may be better to resolve directly. Positron Basic is doing really good with less numbers of commands.
Ignorance comes with a cost

tumbleweed

if( myVar & 4 )

You'd probably find that a decent C compiler for the PIC would translate that to a bit-test too... XC8 does.