Electronics > Microcontrollers

PIC/Hitech C - conversion of char to boolean (bit?)

(1/5) > >>

icon:
Hi

I'm trying to convert my meagre ASM skills into C. I had wrongly assumed that a char (or the result of a char expression) would be understood as 'false' if it equalled 0 (ie 0b00000000) or 'true' if greater than 0 (eg 0b10000000). After an entire afternoon struggling with the logic of a few lines of code, I discover this is not so. Specifically, I'm interested in whether any bits between RB4 and RB7 are low. RB0 to RB3 could be anything. So I do this:
PORTB | 0b00001111

Then I 1's complement the result:
~(PORTB | 0b00001111)

If RB4 to RB7 had been all ones, I would now have an expression that evaluated to 0b00000000; or if (say) RB7 had been 0, then I would have 0b10000000. My intention is to use it in a statement:
if (~PORTB | 0b00001111) {stuff...

In ASM, I could just use comf whatever, btfsc STATUS,Z. Am I missing an obvious construction that would work in C?

Cheers
John

Mechatrommer:

--- Quote ---After an entire afternoon struggling with the logic of a few lines of code
--- End quote ---
yeah! hacking for the one goddamn bit. now you know the fun thing when somebody else encapsulated a funny standard into their library. but i cannot see why "greater or other than zero byte" = false.

Rufus:

--- Quote from: icon on April 28, 2012, 06:56:18 pm ---Am I missing an obvious construction that would work in C?

--- End quote ---

You are probably missing integer promotion rules. Values in expressions are promoted to a minimum size of int before evaluation. For some expressions this makes no difference and the compiler can optimize away the inefficiency, but, not in your case.

(PORTB & 0xF0)

Will be true if any of bits 4 to 7 are set in PORTB.

If you understand assembler looking at the code the compiler generates will help you understand the language. If you are using the free version of Hitech PICC the generated code will horribly inefficient.

IanB:
I think you are doing it backwards.

First mask out the bits you are interested in:

PORTB & 0xF0

Now compare with the all ones value:

(PORTB & 0xF0) == 0xF0

If this expression is true you have all ones. If this expression is false you have one or more zero bits.

IanB:

--- Quote from: icon on April 28, 2012, 06:56:18 pm ---I had wrongly assumed that a char (or the result of a char expression) would be understood as 'false' if it equalled 0 (ie 0b00000000) or 'true' if greater than 0 (eg 0b10000000). After an entire afternoon struggling with the logic of a few lines of code, I discover this is not so.
--- End quote ---

It is indeed so, by the way. That is not what is going wrong. Checking intermediate values with print statements or a debugger would help you see why your code is not working. Spending an afternoon struggling is not good when you could simply debug your code line by line and immediately find where it is not doing what you expect.

[#] Next page

Go to full version