Thursday 15 January 2015

c - Bitwise Operations Help/Suggestions -



c - Bitwise Operations Help/Suggestions -

alright, i'm not looking answers or that. on recent exams, when i've been asked perform relatively simple bitwise operations, can't seem job done. given 30 minutes hour, flush out, 10 minutes or less, stuck.

for example, asked write little function, if x > y,return 1, else 0. couldnt life of me provide answer. after exam, went home , wrote out answer, took me half hour.

im doing best faster @ because know i'm going these kind of questions 1 time again on final.

what rules, axioms, or can utilize help me going on these kind of problems. when see problem this, reasoning helps form answer.

you're going need next general knowledge

understanding of c operators 2's complement arithmetic boolean algebra

a trick may come in handy n-bit folding. example, let's i'm given 32-bit value argument function, , need homecoming 1 if of bits 1, or 0 otherwise. (further assume rules of question don't allow me in sensible fashion.) function this

int hasbitsset( uint32_t value ) { value |= value >> 16; value |= value >> 8; value |= value >> 4; value |= value >> 2; value |= value >> 1; return( value & 1 ); }

the first 5 lines of function "fold" 32-bit value, if bit 1, lsb of result 1. lastly line of function returns lsb. using brute forcefulness boolean algebra, equivalent function is

int hasbitsset( uint32_t value ) { uint32_t bit31 = (value >> 31) & 1; uint32_t bit30 = (value >> 30) & 1; ... uint32_t bit0 = value & 1; return( bit31 | bit30 | ... | bit0 ); }

the point folding useful in reducing amount of code have write, can folding can done brute-force boolean algebra. if you're not sure whether folding work, algebra.

the final thing i'll mention comparisons implemented subtraction. in other words, determine whether x > y, first compute x - y, , check whether result positive. in 2's complement arithmetic, number positive if msb 0 , @ to the lowest degree 1 of other bits 1. extract msb, fold other 31 bits, , utilize boolean algebra generate final result.

that lastly bit of knowledge (comparison equivalence subtraction) problem-specific , troublesome since every question have arcane tidbit of knowledge makes question easier. can pay attending in class , hope little gems stick in mind when they're mentioned.

c bit-manipulation bitwise-operators computer-architecture

No comments:

Post a Comment