Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Bitwise operation

Name: Anonymous 2010-06-09 5:28

How are simple operations like adding and subtraction represented using only bitwise operators such as &, |, ^, >>, ~, and <<?

Also, do each of the bitwise operators perform at the same rate, or are some faster than others?

Name: Anonymous 2010-06-09 11:52


// here's my crude first attempt.
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>

typedef uint8_t U;

U plus(U a, U b) {
    U m = 1, am, bm, c=0, s, r=0;
    while(m) {
        am = !!(a & m);
        bm = !!(b & m);
        s = (am ^ bm);
        if(c) {
            if(!s) {
                r |= m;
                c = am & bm;
            }
        } else {
            if(s)
                r |= m;
            c = am & bm;
        }
        printf("m:%16lu am:%lu bm:%lu c:%lu s:%lu r:%lu\n",m,am,bm,c,s,r);
        m <<= 1;
    }
    return r;
}

int main(int argc, char **argv) {
    U a=0,b=0;
    if(argv[1]) {
        a = atoi(argv[1]);
        if(argv[2]) {
            b = atoi(argv[2]);
        }
    }
    printf("%lu + %lu: %lu\n",a,b,plus(a,b));
    return 0;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List