티스토리 뷰

Study

C(씨) bit(비트) operation(연산) 관련

메디츠 2024. 1. 27. 10:15
반응형

b.zip
0.01MB

 

/*

* bitAnd - x&y using only ~ and |

* Example: bitAnd(6, 5) = 4

* Legal ops: ~ |

* Max ops: 8

* Rating: 1

*/

int bitAnd(int x, int y) {

return ~(~x|~y);

}

 

/*

* bitXor - x^y using only ~ and &

* Example: bitXor(4, 5) = 1

* Legal ops: ~ &

* Max ops: 14

* Rating: 2

*/

int bitXor(int x, int y) {

return (~(~x&~y))&(~(x&y));

}

 

/*

* evenBits - return word with all even-numbered bits set to 1

* Legal ops: ! ~ & ^ | + << >>

* Max ops: 8

* Rating: 2

*/

int evenBits(void) {

int i = 0x55;

 

return (i<<24)|(i<<16)|(i<<8)|i;

 

}

 

/*

* copyLSB - set all bits of result to least significant bit of x

* Example: copyLSB(5) = 0xFFFFFFFF, copyLSB(6) = 0x00000000

* Legal ops: ! ~ & ^ | + << >>

* Max ops: 5

* Rating: 2

*/

int copyLSB(int x) {

return (x<<31)>>31;

 

}

 

/*

* isLessOrEqual - if x <= y then return 1, else return 0

* Example: isLessOrEqual(4,5) = 1.

* Legal ops: ! ~ & ^ | + << >>

* Max ops: 24

* Rating: 3

*/

int isLessOrEqual(int x, int y) {

int x_neg = x>>31;

int y_neg = y>>31;

return ((x_neg & !y_neg) | (!(x_neg ^ y_neg) & (~y+x)>>31));

 

}

 

/*

* logicalNeg - implement the ! operator, using all of

* the legal operators except !

* Examples: logicalNeg(3) = 0, logicalNeg(0) = 1

* Legal ops: ~ & ^ | + << >>

* Max ops: 12

* Rating: 4

*/

int logicalNeg(int x) {

return ((~(~x+1)&(~x))>>31)&1;

 

}

 

/*

* logicalShift - shift x to the right by n, using a logical shift

* Can assume that 1 <= n <= 31

* Examples: logicalShift(0x87654321,4) = 0x08765432

* Legal ops: ~ & ^ | + << >>

* Max ops: 16

* Rating: 3

*/

int logicalShift(int x, int n) {

return (x >> n) & ((1 << (32 + (~n+1))) + ~0);

 

}

 

 

/*

* sum3 - x+y+z using only a single '+'

* Example: sum3(3, 4, 5) = 12

* Legal ops: ! ~ & ^ | << >>

* Max ops: 16

* Rating: 3

*/

/* A helper routine to perform the addition. Don't change this code */

static int sum(int x, int y) {

return x+y;

}

 

int sum3(int x, int y, int z) {

int word1 = sum(x,y);

int word2 = z;

return sum(word1,word2);

}

반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함