180 likes | 312 Views
Bit Operator. Bit operators. ! : invert logical value if value is 0 change to 1, otherwise set to 0 ~ : invert all bits ~0x1010 = 0xefef & : bits ‘and’ operator and | : ‘or’ operator or. Bit operators. ^ : ‘xor’ operator xor + : add << : left bit shifter >> : right bit shifter
E N D
Bit operators • ! : invert logical value • if value is 0 change to 1, otherwise set to 0 • ~ : invert all bits • ~0x1010 = 0xefef • & : bits ‘and’ operator • and • | : ‘or’ operator • or
Bit operators • ^ : ‘xor’ operator • xor • + : add • << : left bit shifter • >> : right bit shifter • warning: it is arithmetic operator( if MSB is 1, go on filling 1 to MSB )
Our program restrictions • We are only allowed to use the following eight operations( or more fewer op. depending each problem ) • ! ~ & ^ | + << >> • any constants longer than 8bits is not allowed • max constant is 0xff
file download • wget http://aces.snu.ac.kr/~jongyoung/lecture/pa01.tar • tar -xvf pa01.tar • We modify only bits.c • dlc check our program whether coding rule is correct • btest check our ‘bits.c’ correctness
Goal • Modify functions in bits.c to same result what we expected.
bitAnd • Using de morgan’s law • ~(A and B) = ~A or ~B • Only use the operation ~ and |
bitXor • Using only the operation & and ~ • Similar as bitAnd
evenBits • Return a word with all even-numbered bits set to 1 • Sequence add and bit-shift for some constant. • Careful for constant’s length
bitMask • First, make 32bit constant that all bits are ‘1’ • properly shift • If lowbit >= highbit, then the mask should be all 0’s • bitMask(5,3) returns 0x38
bitParity • Reduce problem’s complexity by folding input variable • Return 1 if x contains an odd number of 0’s. • bitParity(5) = 0, bitParity(7) = 1
fitsBit • Divide input into positive and negative. • Return 1 if x can be represented as an n-bit, two’s complement integer, where 1 <= n <= 32. • fitsBit(5,3) returns 0 • fitsBit(-4,3) returns 1
sm2tc • Convert from sign-magnitude to two’s complement where the MSB is the sign bit • Extract sign bit and others • Sm2tc(0x80000005) returns -5