12
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

うるう年判定:ビット演算&LUT利用

Last updated at Posted at 2016-02-06

http://qiita.com/le_panda_noir/items/70eaab385c2b33c8fb63 より

うるう年判定器

uint64_t leapyear_lut[] =
  {0x1111111111111111, 0x1111110111111111,
   0x1111111111111111, 0x1111111111111011,
   0x1111011111111111, 0x1111111111111111,
   0x1111111111111111, 0x1111111111111111};

int is_leapyear(int year) {
  year %= 400;
  return !!(leapyear_lut[year >> 6] & (1ULL << (year & 0x3f)));
}

ルックアップテーブル(LUT)生成

# include <inttypes.h>
# include <stdio.h>

int main()
{
  uint64_t lut[8];
  int exclude[] = {100, 200, 300};
  int i;

  for (i = 0; i < 8; i++)
    lut[i] = 0x1111111111111111ULL;
  for (i = 0; i < 3; i++) {
    int year = exclude[i];
    lut[year >> 6] &= ~(1ULL << (year & 0x3f));
  }

  printf("uint64_t leapyear_lut[] = {");
  for (i = 0; i < 8; i++)
    printf("%s0x%016" PRIx64, (i ? "," : ""), lut[i]);
  printf("};\n");
}

うるう年判定器(圧縮版)

uint64_t leapyear_lut[] = {0xfffbfffffdffffff,0xfffffffffffff7ff};

int is_leapyear(int year) {
  if (year & 3) return 0;
  int x = (year >> 2) % 100;
  return !!(leapyear_lut[x >> 6] & (1ULL << (x & 0x3f)));
}

ルックアップテーブル(LUT)生成

# include <inttypes.h>
# include <stdio.h>

int main() {
  uint64_t lut[2] = { ~0UL, ~0UL };
  int exclude[] = {100, 200, 300};

  for (int i = 0; i < 3; i++) {
    int x = exclude[i] >> 2;
    lut[x >> 6] &= ~(1ULL << (x & 0x3f));
  }
  printf("uint64_t leapyear_lut[] = "
   "{0x%016"PRIx64",0x%016"PRIx64"};", lut[0], lut[1]);
}
12
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?