#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <string>
#include <math.h>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <cmath>
#pragma warning(disable:4996)
#define Zero(a) memset(a, 0, sizeof(a))
#define Neg(a) memset(a, -1, sizeof(a))
#define All(a) a.begin(), a.end()
#define PB push_back
#define repf(i,a,b) for(i = a;i <= b; i++)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define root 1,n,1
#define ld rt << 1
#define rd rt << 1 | 1
#define ll long long
#define MAXN 100100
#define INF 6666666
#define mod 1000000007
#define ll long long
#define sqrtt(x) (ll)(x)*(x)
#define dist(x1,y1,x2,y2) (sqrtt(x1-x2)+sqrtt(y1-y2))
using namespace std;
ll x, y;
ll k;
int T;
int yess[130];
vector<int>rec;
string Sum(string s1, string s2)
{
if (s1.length() < s2.length())
{
string temp = s1;
s1 = s2;
s2 = temp;
}
int i, j;
for (i = s1.length() - 1, j = s2.length() - 1; i >= 0; i--, j--)
{
s1[i] = char(s1[i] + (j >= 0 ? s2[j] - '0' : 0));
if (s1[i] - '0' >= 10)
{
s1[i] = char((s1[i] - '0') % 10 + '0');
if (i) s1[i - 1]++;
else s1 = '1' + s1;
}
}
return s1;
}
ll multt(ll m, ll n) {
ll ans = 1;
for (int i = 0; i < n; ++i)
ans *= m;
return ans;
}
string Multiply(string s, int x) //大数乘以整形数
{
reverse(s.begin(), s.end());
int cmp = 0;
for (int i = 0; i < s.size(); i++)
{
cmp = (s[i] - '0')*x + cmp;
s[i] = (cmp % 10 + '0');
cmp /= 10;
}
while (cmp)
{
s += (cmp % 10 + '0');
cmp /= 10;
}
reverse(s.begin(), s.end());
return s;
}
struct node {
int val;
int pos;
};
vector<node>nd;
int main() {
while (cin >> T) {
while (T--) {
cin >> x >> k;
rec.clear();
for (int i = 0; i < 130; ++i)
yess[i] = 1;
ll tt = 0;
int stp = 0;
while (tt <= x) {
if (multt(2, stp) & x) {
yess[stp] = 0;
}
tt += multt(2, stp);
stp++;
}
nd.clear();
int cnt = 0;
for (int i = 0; i < 130; ++i) {
node kk;
if (yess[i] == 1) {
kk.pos = 1;
kk.val = i;
nd.push_back(kk);
}
}
//cout << nd.size() << endl;
stp = 0;
tt = 0;
while (stp < nd.size()) {
if ((multt(2, stp) & k) && tt <= k) {
nd[stp].pos = 1;
}
else {
nd[stp].pos = 0;
}
tt += multt(2, stp);
stp++;
}
vector<node>ndd;
for (int i = 0; i < nd.size(); ++i) {
if (nd[i].pos == 1)
ndd.push_back(nd[i]);
}
string ans = "0";
for (int i = 0; i < ndd.size(); ++i) {
string anss = "1";
for (int j = 0; j < ndd[i].val; ++j)
anss = Multiply(anss, 2);
//cout << anss << endl;
ans = Sum(ans, anss);
}
cout << ans << endl;
}
}
return 0;
}