T = int(input()) for _ in range(T): x, y = map(int, input().split()) if not x >> y & 1: print(0) elif y == 0 and (x - 1) % 4 == 0: print(1) elif ((x - 1) % 8 == 1 and y == 1) or ((x - 1) % 8 == 2 and y in [0, 1]): print(3) else: cnt = 0 while 2**(cnt+1) <= x: cnt += 1 cnt -= 2 # 何番目のピラミッドか s = 3 + cnt # 各ピラミッドの一番下 for i, j in enumerate(range(cnt+2, 0, -1)): s += j * 2**i print(s)