How to set and clear bits without operator ~

I use C as a script for the Bluegiga chip, and their script langauge does not have a statement ~in the compiler. Is there a way to work with bits using pure math? For example, I am reading a byte, and I need to clear bit 1 and set bit 2.

The following bitwise operations are supported:
Operation              Symbol
 AND                     &
 OR                      |
 XOR                     ^
 Shift left              <<
 Shift right             >>

The following mathematical operators are supported:
Operation              Symbol
 Addition:               +
 Subtraction:            -
 Multiplication:         *
 Division:               /
 Less than:              <
 Less than or equal:     <=
 Greater than:           >
 Greater than or equal:  >=
 Equals:                 =
 Not equals:             !=
+3
source share
4 answers

Just use the OR and AND operations. To perform this operation:

start byte: 0000 0001

clear bit 1: 0000 0001 and 1111 1110 → the result is 0000 0000 (1 bit of the second operand must be 0 to clear the bit)

now set bit 2: 0000 0000 | 0000 0010 → the result is 0000 0010 (the 2nd bit of the second operand must be 1 to set the bit)

, , .

, , : n - 2 ^ n

n - 1111 1111 XOR 2 ^ n ( 1111 1111 XOR).

+2

~, , XOR .

#include<stdio.h>

int main()
{
    unsigned int s = 0xFFFFFFFF ;

    printf("%#x" , 0xFF ^ s ) ;  //XOR with the constant is equivalent to ~


    unsigned int byte = 0x4 ;
    printf("%#x" , 0x5 & ( byte ^ s ) ) ; //clear those bits

return 0 ;
}

~, .

+1

() SET, INVERT ( xor). .

 aabbccdd  <-- original value
 00000110   OR                
 00000010  XOR
 --------
 aabbc10d  <-- result (I'm counting the bits from 7 downto 0)

.

+1

XOR -1 .

0
source

All Articles