컴공생의 다이어리

[c] (7,4)Hamming Code Encoder(인코더)와 Decoder(디코더) 본문

Development/C & C++

[c] (7,4)Hamming Code Encoder(인코더)와 Decoder(디코더)

컴공 K 2021. 6. 10. 00:01

(7,4)Hamming Code Encoder(인코더) Code

 - Encoder의 입력은 4bit, 출력은 7bit의 codeword

// (7,4) Hamming code Encoder
#include<stdio.h>
#include<string.h>

int main() {
	char input[5] = { 0 };
	int s[4] = { 0, };
	int t[7] = { 0, };
	int G_T[7][4] = {
		{1,0,0,0},	{0,1,0,0},	{0,0,1,0},
		{0,0,0,1},	{1,1,1,0},	{0,1,1,1},	{1,0,1,1}
	};
	char result[8] = { 0 };

	printf("--------- (7,4)Hamming Code Encoder ---------\n");
	printf("Input: ");
	scanf("%s",input);
	for (int i = 0; input[i]; i++) {
		s[i] = input[i] - '0';
	}
	for (int i = 0; i < 7; i++) {
		for (int j = 0; j < 4; j++) {
			t[i] += (G_T[i][j] * s[j]);
		}
	}
	for (int i = 0; i < 7; i++) {
		t[i] %= 2;
	}
	sprintf(result, "%d%d%d%d%d%d%d", t[0], t[1], t[2], t[3], t[4], t[5], t[6]);
	printf("Output: %s\n", result);
	return 0;
}

 

 

(7,4)Hamming Code Decoder(디코더) Code

 - Decoder의 입력은 7bit 의 codeword, 출력은 Error가 수정된 4bit의 data

// (7,4) Hamming code Decoder
#include<stdio.h>
#include<string.h>

int main() {
	char input[8] = { 0 };
	int H[3][7] = {
		{1,1,1,0,1,0,0},
		{0,1,1,1,0,1,0},
		{1,0,1,1,0,0,1}
	};
	int r[7] = {0,};
	int z[3] = { 0, };
	int syndrome[8] = {0,7,6,4,5,1,2,3};
	char result[5] = { 0 };

	printf("--------- (7,4)Hamming Code Decoder ---------\n");
	printf("Input: ");
	scanf("%s",input);
	for (int i = 0; input[i]; i++) {
		r[i] = input[i] - '0';
	}
	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < 7; j++)
			z[i] += (H[i][j] * r[j]);
	}
	for (int i = 0; i < 3; i++)
		z[i] %= 2;

	int temp = z[0] * 4 + z[1] * 2 + z[2];
	if (temp != 0) {
		if (r[syndrome[temp] - 1] == 1)
			r[syndrome[temp] - 1] = 0;
		else
			r[syndrome[temp] - 1] = 1;
	}
	sprintf(result, "%d%d%d%d", r[0], r[1], r[2], r[3]);
	printf("Output: %s\n", result);
	return 0;
}
728x90
Comments