그레이 부호

위키백과, 우리 모두의 백과사전.

비트 너비 별 그레이 부호
2비트 4비트
00
01
11
10

0000
0001
0011
0010
0110
0111
0101
0100
1100
1101
1111
1110
1010
1011
1001
1000
3비트
000
001
011
010
110
111
101
100

그레이 부호 또는 그레이 코드(gray code이진법 부호의 일종으로, 연속된 수가 1개의 비트만 다른 특징을 지닌다. 연산에는 쓰이진 않고 주로 데이터 전송, 입출력 장치, 아날로그-디지털 간 변환과 주변장치에 쓰인다.[1]

역사[편집]

그레이의 특허 앞장의 일부. 바이너리 코드(15)의 PCM 튜브(10)를 보여주고 있다.

그레이 부호로의 변환[편집]

C에서 다음의 함수는 이진 숫자와 관련 그레이 부호 간의 변환을 나타낸다. 그레이 대 이진 변환이 각 비트가 한 번에 처리되어야 하는 것처럼 보이지만, 더 빠른 알고리즘들이 존재한다.[2]

/*
 * This function converts an unsigned binary
 * number to reflected binary Gray code.
 *
 * The operator >> is shift right. The operator ^ is exclusive or.
 */
unsigned int binaryToGray(unsigned int num)
{
    return num ^ (num >> 1);
}

/*
 * This function converts a reflected binary
 * Gray code number to a binary number.
 * Each Gray code bit is exclusive-ored with all
 * more significant bits.
 */
unsigned int grayToBinary(unsigned int num)
{
    unsigned int mask;
    for (mask = num >> 1; mask != 0; mask = mask >> 1)
    {
        num = num ^ mask;
    }
    return num;
}

/*
 * A more efficient version, for Gray codes of 32 or fewer bits.
 */
unsigned int grayToBinary32(unsigned int num)
{
    num = num ^ (num >> 16);
    num = num ^ (num >> 8);
    num = num ^ (num >> 4);
    num = num ^ (num >> 2);
    num = num ^ (num >> 1);
    return num;
}

각주[편집]

  1. 이한출판사 출판, 《컴퓨터 구조》 오상엽 저. p.150
  2. Henry Gordon Dietz. "The Aggregate Magic Algorithms: Gray Code Conversion"