Last active
October 1, 2018 22:56
-
-
Save gabrielfern/9727a0e89fdb60272e289aab82dfb089 to your computer and use it in GitHub Desktop.
Detecção de erro por paridade
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <assert.h> | |
// Implementado paridade par | |
/* retorna 0 caso não tenha erro de paridade | |
retorna 1 caso exista erro de paridade */ | |
int checa_erro(void *dados, unsigned tamanho) { | |
unsigned long total = 0; | |
while (tamanho > 0) { | |
unsigned char byte = ((char *) dados)[tamanho-1]; | |
while (byte > 0) { | |
if (byte & 1 == 1) | |
total++; | |
byte >>= 1; | |
} | |
tamanho--; | |
} | |
return total % 2 == 0 ? 0 : 1; | |
} | |
int main() { | |
char dados[] = {128, 3, 255}; | |
// 128 em binário é 10000000, 1 bit 1 | |
assert(checa_erro(dados, 1) == 1); | |
// 3 em binário é 00000011, 2 bits 1 | |
assert(checa_erro(dados+1, 1) == 0); | |
// 255 em binário é 11111111, 8 bits 1 | |
assert(checa_erro(dados+2, 1) == 0); | |
// 111111110000001110000000, 11 bits 1 | |
assert(checa_erro(dados, 3) == 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment