#include <bits/stdc++.h>
using namespace std;
int q, num[110], dig[110];
long long qpow(long long x, int n) {
  long long ans = 1;
  for (; n; n >>= 1, x = x * x)
    if (n & 1) ans = ans * x;
  return ans;
}
long long calc(int m, int tot, int maxnow) {
  long long ans = 0;
  for (int t = 15; t >= maxnow; t--) {
    int x = t / 4 + 1;
    int tmp = t % 4;
    if (x > tot) continue;
    for (int S = 0; S < (1 << 3); S++) {
      int now = (1 << (tmp));
      for (int i = 0; i < 3; i++)
        if ((1 << (i)) & S) now |= (1 << ((tmp + i + 1) % 4));
      if (now > t || (dig[x] != -1 && dig[x] != now)) continue;
      int cnt = m;
      if (dig[x] == -1) cnt--;
      if (now == t || maxnow == t)
        ans += qpow(t + 1, cnt);
      else
        ans += qpow(t + 1, cnt) - qpow(t, cnt);
    }
  }
  return ans;
}
long long calc(char *S, bool inc) {
  memset(num, 0, sizeof(num));
  int tot = strlen(S);
  for (int i = 0; i < tot; i++) {
    if (S[i] <= '9' && S[i] >= '0')
      num[tot - i] = S[i] - '0';
    else
      num[tot - i] = S[i] - 'a' + 10;
  }
  if (inc) {
    num[1]++;
    for (int i = 1; i <= tot; i++)
      if (num[i] >= 16) num[i] -= 16, num[i + 1]++;
    if (num[tot + 1]) tot++;
  }
  for (int i = 1; i <= tot; i++) dig[i] = -1;
  long long ans = 0;
  int maxnow = 0;
  for (int i = tot; i >= 1; i--) {
    for (int j = 0; j < num[i]; j++)
      dig[i] = j, ans += calc(i - 1, tot, max(maxnow, j));
    dig[i] = num[i];
    maxnow = max(maxnow, dig[i]);
  }
  return ans;
}
char L[110], R[110];
int main() {
  int q;
  cin >> q;
  while (q--) {
    cin >> L >> R;
    cout << calc(R, 1) - calc(L, 0) << endl;
  }
  return 0;
}
