2
2

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.

[C言語]ハミング重みとハミング距離を求める

Last updated at Posted at 2018-07-11

ハミング重みと距離の求め方の備忘録
##ハミング重み

ハミング重みとは、シンボル列中の 0 以外のシンボルの個数である。典型的には、ビット列中の1の個数として使われる。(Wikipedia)

#include <stdio.h>
#include <stdint.h>

uint32_t HammingWeight(uint32_t);

int main() {
    int n;

    printf("n = ? ");
    scanf("%d", &n);
    printf("Hamming weight = %d\n", HammingWeight(n));

    return 0;
}

uint32_t HammingWeight(uint32_t n)
{
    n = (n & 0x55555555) + (n >> 1 & 0x55555555);
    n = (n & 0x33333333) + (n >> 2 & 0x33333333);
    n = (n & 0x0f0f0f0f) + (n >> 4 & 0x0f0f0f0f);
    n = (n & 0x00ff00ff) + (n >> 8 & 0x00ff00ff);
    return (n & 0x0000ffff) + (n >>16 & 0x0000ffff);
}
実行結果1
>n = ? 7
Hamming weight = 3

実行結果2
>n = ? 2147483647
Hamming weight = 31

##ハミング距離

ハミング距離とは、等しい文字数を持つ二つの文字列の中で、対応する位置にある異なった文字の個数である。(Wikipedia)

ハミング距離は関数に渡す際、排他的論理和を取ればよい

#include <stdio.h>
#include <stdint.h>

uint32_t HammingDistance(uint32_t);

int main() {
    uint32_t a, b;

    scanf("%d", &a);
    scanf("%d", &b);
    printf("Hamming Distance = %d\n", HammingDistance(a ^ b));

    return 0;
}

uint32_t HammingDistance(uint32_t n)
{
    n = (n & 0x55555555) + (n >> 1 & 0x55555555);
    n = (n & 0x33333333) + (n >> 2 & 0x33333333);
    n = (n & 0x0f0f0f0f) + (n >> 4 & 0x0f0f0f0f);
    n = (n & 0x00ff00ff) + (n >> 8 & 0x00ff00ff);
    return (n & 0x0000ffff) + (n >>16 & 0x0000ffff);
}
実行結果1
>10
>10
Hamming Distance = 0

実行結果2
>0
>2147483647
Hamming Distance = 31
2
2
1

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?