Is it possible to implement bitwise operators using integer arithmetic?

后端 未结 6 1297
青春惊慌失措
青春惊慌失措 2021-01-29 22:05

I am facing a rather peculiar problem. I am working on a compiler for an architecture that doesn\'t support bitwise operations. However, it handles signed 16-bit integer arithme

6条回答
  •  囚心锁ツ
    2021-01-29 22:38

    As long as you're willing for it to be very expensive, yes.

    Basically, you'll explicitly put a number into a base-2 representation. You do this just as you would put a number into base-10 (e.g., to print it out), that is, by repeated division.

    This turns your number into an array of bools (or ints in the range 0,1), then we add functions to operate on those arrays.

    again, not that this is tremendously more expensive than bitwise operations, and that almost any architecture will supply bitwise operators.

    In C (of course, in C you have bitwise operators, but...) an implementation might be:

    include 
    const int BITWIDTH = CHAR_BIT;
    typedef int[BITWIDTH] bitpattern;
    
    // fill bitpattern with base-2 representation of n
    // we used an lsb-first (little-endian) representation
    void base2(char n, bitpattern array) {
      for( int i = 0 ; i < BITWIDTH ; ++i ) {
        array[i] = n % 2 ;
        n /= 2 ;
      }
    }
    
    void bitand( bitpattern op1, bitpattern op2, bitpattern result ) {
      for( int i = 0 ; i < BITWIDTH ; ++i ) {
        result[i] = op1[i] * op2[i];
      }
    }
    
    
    void bitor( bitpattern op1, bitpattern op2, bitpattern result ) {
      for( int i = 0 ; i < BITWIDTH ; ++i ) {
        result[i] = (op1[i] + op2[i] != 0 );
      }
    }
    
    // assumes compiler-supplied bool to int conversion 
    void bitxor( bitpattern op1, bitpattern op2, bitpattern result ) {
      for( int i = 0 ; i < BITWIDTH ; ++i ) {
        result[i] = op1[i] != op2[i]  ;
      }
    }
    

提交回复
热议问题