bit manipulation - Java simple bitwise operation -
we given integer n, value v (v=0 or 1) , position p. write sequence of operators modifies n hold value v @ position p binary representation of n. example:
- n = 5 (00000101), p=3, v=1 -> 13 (00001101)
- n = 5 (00000101), p=2, v=0 -> 1 (00000001)
this code:
int n1 = 35; int p1 = 3; int v = 1; n1 = n1 + (v << p1); system.out.println(n1);
it works when v=1 when v=0 doesn't.
since want "set" index value, need 1 of 2 operations
'and' set 0 values @ index 0, won't work 1 values 'or' set 1 values @ index 1, won't work 0 values
now need put right number @ right index. can done shifting 1.
'<<' moves 1 number of places
for example
'1 << 3' shifts 1 3 places, resulting in '00001000'
remember, need 0 of operations, 0 in place, need invert bits
'not' or '~' flips bits in number ~00001000 yeilds 11110111
now can have 1 or 0 in index wish, , need use if statement pick right 1 based on desired operation , apply corresponding and
or or
operation set bit want.
Comments
Post a Comment