summaryrefslogtreecommitdiffstats
path: root/stm32/app/gen/c.c
blob: 56e723793f4cf7bb48fbac2e1c1e939900b2b57d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

uint8_t crc_table[256];

uint8_t flip_byte (uint8_t value)
{
  value = ((value >> 1) & 0x55) | ((value & 0x55) << 1);
  value = ((value >> 2) & 0x33) | ((value & 0x33) << 2);
  value = ((value >> 4) & 0x0F) | ((value & 0x0F) << 4);
  return value;
}


uint8_t
crc8 (uint8_t * data, size_t len)
{
  unsigned i, j;
  uint8_t crc = 0, b;

  for (i = 0; i < len; ++i, ++data)
    {

      b = *data;
      for (j = 0; j < 8; j++)
        {
          if ((crc >> 7) ^ (b & 1))
            {
              crc = (crc << 1) ^ 7;
            }
          else
            {
              crc = crc << 1;
            }

          b >>= 1;
        }
    }
  return crc;
}

void
make_table (void)
{
  unsigned i;
  unsigned j;
  uint8_t  b;

  for (i = 0; i < 256; ++i)
    {
      b = i;
      for (j = 0; j < 8; j++)
        {
	  
          if (b & 1)
            {
              b = (b >> 1 ) ^ 0xe0;
            }
          else
            {
              b = b >> 1;
            }

        }
      crc_table[i] = b;
    }
}

uint8_t
crc8_better (uint8_t * data, size_t len)
{
  uint8_t crc = 0;
  unsigned i;

  for (i = 0; i < len; i++, data++)
    {
      crc = crc_table[crc ^ *data];
    }

  return flip_byte(crc);
}



int
main (int argc, char *argv[])
{
  uint8_t fish[4] = "\5\0\1\301"; 
  size_t l;

  make_table ();

  for (l=0;l<256;++l) {
	printf("0x%02x, ",crc_table[l]);
  }

  printf("\n");

  for (l=0;l<4;++l ) {
  printf ("%u %02x %02x %02x\n",(unsigned)l, crc8 (fish, l), crc8_better (fish, l), fish[l]);
  }

  

  return 0;
}