You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all of M. That is, if M = 10011, you can assume that there are at least 5 bits between j and i. You would not, for example, have j = 3 and i = 2, because M could not fully fit between bit 3 and bit 2.
In [26]:
bit = 0xFFFF
M = 0x5
N = 0xF00F
def insertion(M, N, i, j):
ALL = 0xFFFFFFFF
left_mask = ALL << j + 1
print(bin(ALL))
print("left_mask:" + bin(left_mask))
right_mask = ALL >> (32 - i)
mask = left_mask|right_mask
print(bin(mask))
M_ = (M << i)
ret = (N&mask) | M_
print(bin(M_))
print(bin(ret))
return ret
print(bin(insertion(M, N, 3, 5)))
In [46]:
def bin_to_str(number):
strs = []
remain = number
for i in range(1, 31):
if remain == 0:
break
elif remain - 0.5**i >= 0:
remain = remain - 0.5**i
strs.append(str(1))
else:
strs.append(str(0))
print(remain, 0.5**i)
if remain > 0:
return "ERROR"
else:
return "0." + "".join(strs)
print(bin_to_str(0.875))
In [ ]: