This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

How can I exchange two bits?

The following does not work (ACC is always 0, despite out[0] is 255):

ACC0 = out[0] & 1 == 1 ? 1 : 0;
ACC1 = out[0] & 2 == 2 ? 1 : 0;
out[0] &= 0xFC;
send_string(" acc1");
send_byte(ACC);
if (ACC0)
out[0] |= 2;
if (ACC1)
out[0] |= 1;

Parents
  • Well, there's the straightforward way:

    bit temp;
    
    // save bit 0
    temp = out[0] & 1;
    
    // bit 0 = bit 1
    out[0] &= ~1;
    out[0] |= (out[0] & 2) ? 1 : 0;
    
    // bit 1 = temp
    out[0] &= ~2;
    out[0] |= temp ? 2 : 0;
    
    

    You could also use a shift instead of the conditional to get bit 1 to bit 0.

    // bit 0 = bit 1
    out[0] |= (out[0] >> 1) & 1;

    Or you could use the bit-addressable memory if you have a byte to spare in this function.

    bit tempBit;
    
    // temporary swap area
    bdata temp;
    sbit temp0 = temp^0;
    sbit temp1 = temp^1;
    
    temp = out[0];
    
    tempBit = temp0;
    temp0 = temp1;
    temp1 = tempBit;
    
    out[0] = temp;
    

    If you don't care about the other bits in out[0], you could save the use of tempBit. Or, you could use the old XOR swap trick on the bit variables:

    temp0 = temp0 ^ temp1;
    temp1 = temp0 ^ temp1;
    temp0 = temp0 ^ temp1;
    

    I haven't compiled any of these to see what the generated code might look like.

Reply
  • Well, there's the straightforward way:

    bit temp;
    
    // save bit 0
    temp = out[0] & 1;
    
    // bit 0 = bit 1
    out[0] &= ~1;
    out[0] |= (out[0] & 2) ? 1 : 0;
    
    // bit 1 = temp
    out[0] &= ~2;
    out[0] |= temp ? 2 : 0;
    
    

    You could also use a shift instead of the conditional to get bit 1 to bit 0.

    // bit 0 = bit 1
    out[0] |= (out[0] >> 1) & 1;

    Or you could use the bit-addressable memory if you have a byte to spare in this function.

    bit tempBit;
    
    // temporary swap area
    bdata temp;
    sbit temp0 = temp^0;
    sbit temp1 = temp^1;
    
    temp = out[0];
    
    tempBit = temp0;
    temp0 = temp1;
    temp1 = tempBit;
    
    out[0] = temp;
    

    If you don't care about the other bits in out[0], you could save the use of tempBit. Or, you could use the old XOR swap trick on the bit variables:

    temp0 = temp0 ^ temp1;
    temp1 = temp0 ^ temp1;
    temp0 = temp0 ^ temp1;
    

    I haven't compiled any of these to see what the generated code might look like.

Children