Created
October 15, 2017 09:04
-
-
Save benpicco/5d804858ca889792631992ff85e9c342 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <stdbool.h> | |
#include <stdio.h> | |
#include <stdint.h> | |
static const int bits_per_nibble[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; | |
#define BITS_PER_U8(x) (bits_per_nibble[(x) & 0xf] + bits_per_nibble[((x) >> 4) & 0xf]) | |
#define BITS_PER_U16(x) (BITS_PER_U8((x) & 0xff) + BITS_PER_U8(((x) >> 8) & 0xff)) | |
#define __builtin_popcount(x) (BITS_PER_U16((x) & 0xffff) + BITS_PER_U16(((x) >> 16) & 0xffff)) | |
#define SERIAL_FLAG_EXT_PAREN (1 << 6) | |
#define SERIAL_FLAG_EXT_PARODD (1 << 7) | |
uint8_t set_parity(uint8_t flags, uint8_t flags_ext) { | |
flags_ext |= SERIAL_FLAG_EXT_PAREN; | |
flags_ext &= ~SERIAL_FLAG_EXT_PARODD; | |
if (1 & (BITS_PER_U8(flags) + BITS_PER_U8(flags_ext))) | |
return flags_ext | SERIAL_FLAG_EXT_PARODD; | |
return flags_ext; | |
} | |
bool check_parity(uint8_t flags, uint8_t flags_ext) { | |
if ((flags_ext & SERIAL_FLAG_EXT_PAREN) == 0) { | |
printf("no parity\n"); | |
return false; | |
} | |
return 1 & (BITS_PER_U8(flags) + BITS_PER_U8(flags_ext)); | |
} | |
int main(void) { | |
uint8_t flags = 0b00000000; | |
uint8_t flags_ext = 0b00000000; | |
for (uint8_t i = 0; i < 64; ++i) { | |
flags_ext = i; | |
for (flags = 0; flags < 0xff; ++flags) { | |
flags_ext = set_parity(flags, flags_ext); | |
printf("%02x%02x\n", flags, flags_ext); | |
if (check_parity(flags, flags_ext)) { | |
printf("parity error!\n"); | |
return 1; | |
} | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment