|
|
1.1 ! root 1: #print ! 2: The problem is to produce a function ! 3: bitct(x) ! 4: which examines the bits in x, returning a count of ! 5: the number of 1-bits. There are various ways of doing ! 6: this job: here are two. ! 7: (1) a sane way. Shift the word x right 16 times (you are ! 8: on UNIX) and check the rightmost bit each time, counting ! 9: the number of times it is '1'. ! 10: (2) a machine-independent (sort of) way. The logical ! 11: bitwise AND of x and x-1 contains one fewer one bit than x itself. ! 12: Loop anding x and x-1 until you get zero. ! 13: Program either algorithm. Compile and test it. Leave it on ! 14: a file bitct.c and type "ready". ! 15: #once #create tzaqc.c ! 16: main() ! 17: { ! 18: int x; ! 19: x=23069; ! 20: if (bitct(x) != goodct(x)) ! 21: return(1); ! 22: x=0; ! 23: if (bitct(x) != goodct(x)) ! 24: return(1); ! 25: x=16384; ! 26: if (bitct(x) != goodct(x)) ! 27: return(1); ! 28: x = -1; ! 29: if (bitct(x) != goodct(x)) ! 30: return(1); ! 31: x= -200; ! 32: if (bitct(x) != goodct(x)) ! 33: return(1); ! 34: return(0); ! 35: } ! 36: goodct(x) ! 37: { ! 38: int k, i; ! 39: for(k=i=0; i<16; i++) ! 40: { ! 41: k =+ (x&1); ! 42: x= x>>1; ! 43: } ! 44: return(k); ! 45: } ! 46: #user ! 47: cc tzaqc.c bitct.o ! 48: a.out ! 49: #succeed ! 50: /* a possible solution */ ! 51: bitct(x) ! 52: { ! 53: int k, i; ! 54: ! 55: for(i=k=0; i<16; i++) { ! 56: if (x&1) ! 57: k++; ! 58: x >>= 1; ! 59: } ! 60: return(k); ! 61: } ! 62: /* by the way, if you really care about ! 63: this problem a table lookup by whole bytes ! 64: is faster */ ! 65: #log ! 66: #next ! 67: 42.1a 10
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.