import sys input = sys.stdin.readline def distance(R,C,x,y): #print(R,C,x,y) if R==x and C==y: return 0 ind=-1 for i in range(y-1,C-1,-1): if R & (1<=x): return max(abs(x-R),abs(y-C)) #(1<=mid: if C==b-1: return R else: return mid+calc(b-1,R-mid,C,0) else: return mid +1+ distance(R,C,mid-1,b-2) else: if b==3: if R==1: return 3 if R==2: return 2 if R==3: if C==1: return 2 else: return 1 if b==2: return 1 mid=2**(b-2) if R>=mid: #print("!",b-C,2**(b-1)-R) return 1+ calc(b-1,R-mid,C,1) else: return 2**(b-2) + calc(b-1,R,C,1) return 0 T=int(input()) for tests in range(T): R,C=map(int,input().split()) b=R.bit_length() if C==b: print(R-1) continue #print(b) M=2**b-1 m=2**(b-1) mid=(m+M+1)//2 if R>=mid and C==b-1: print(R-1) continue #print(m,M,mid) #print(b,R-m,C,0) ANS=m-1 ANS+=calc(b,R-m,C,0) print(ANS)