Define bit vs. bit masking

Discussion in 'Programmer's Corner' started by ke5nnt, Jan 3, 2015.

  1. ke5nnt

    Thread Starter Active Member

    Mar 1, 2009
    384
    15
    Is defining a bit in C, such as:

    #define Output_1 PORTAbits.RA0

    The same thing as masking the same bit:

    #define Output_1mask 0b00000001

    Will this function the same when using bitwise operators?

    Output_1 & other vs. Output_1mask & other

    Thanks.
     
  2. MrChips

    Moderator

    Oct 2, 2009
    12,449
    3,365
    My guess would be that they are not the same.

    Bit masking clearly uses bitwise logical operators whereas PORTAbits.RA0 is a structure using unions.

    How the actual code is compiled and implemented will depend on the compiler and the native MCU instruction set.
    Some MCUs have direct bit addressing instructions. MCUs that cannot address individual bits will have to resort to bitwise logical operators using masks.
     
  3. joeyd999

    AAC Fanatic!

    Jun 6, 2011
    2,692
    2,760
    In C, in most cases a #define is simply text substitution.

    In your example, all occurrences of Output_1 will be replaced, prior to compilation, with the text 'PORTAbits.RA0'. All occurrences of Output_1mask will be replaces with the text '0b00000001'.

    Now, tell me if the contruct:

    Output_1 & other

    makes sense.
     
  4. ErnieM

    AAC Fanatic!

    Apr 24, 2011
    7,395
    1,607
    They work about the same, but by that I mean since "other" is not defined neither way will compile.
     
  5. ke5nnt

    Thread Starter Active Member

    Mar 1, 2009
    384
    15
    I appreciate all the responses, and sorry for my delayed response. I believe I have a grasp on the differences now.

    Best
     
  6. Papabravo

    Expert

    Feb 24, 2006
    10,168
    1,797
    One of them is an address and the other is just a numerical constant.
    The constant is used to do operation on a bit with bytewide operations.
    The address is used by specific operations that work on bits.
     
Loading...