Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/zhenxiangba/zhenxiangba.com/public_html/phproxy-improved-master/index.php on line 456
/*
* crc8.c - 8ビットCRCの計算
*
* revision history:
* 0.0: Dec. 16, 2021 by Dai ISHIJIMA
*
* 参考文献:
* W.H.Press, et al.: Numerical Recipes in C
* (Cambridge University Press, 1992) 2nd ed., pp.896-901.
*/
#include
#include
#include /* strtol(3) */
#define EOS '\0'
#define shift --argc; ++argv
char *prog;
/* 8 7654 3210 dallas-maxim */
#define GX 0x131 /* 1 0011 0001: G(x) = x^8 + x^5 + x^4 + 1 */
#define INI 0xff /* initial value */
#define P ((GX) & 0xff) /* Polynomial */
unsigned char rawcrc8(unsigned char p, unsigned char crc, unsigned char ch)
{
int bit;
crc ^= ch;
for (bit = 0; bit < 8; bit++) {
if (crc & 0x80) {
crc <<= 1;
crc ^= p;
}
else {
crc <<= 1;
}
}
return(crc);
}
unsigned char crc8s(unsigned char ini, unsigned char p,
int len, unsigned char *s)
{
int i;
unsigned char crc;
crc = ini;
for (i = 0; i < len; i++) {
crc = rawcrc8(p, crc, s[i]);
}
return(crc);
}
void calc(FILE *fp, int p, int ini)
{
int len;
unsigned char buf[BUFSIZ];
if ((len = fread(buf, 1, BUFSIZ - 1, fp)) > 0) {
printf("%02x\n", crc8s(ini, p, len, buf));
}
}
void usage()
{
fprintf(stderr, "Usage: %s [options] [file]\n", prog);
fprintf(stderr, " options:\n");
fprintf(stderr, "\t-g GX (HEX) / -G GX (DEC)\n");
fprintf(stderr, "\t-p polynomial (HEX) / -p polynomial (DEC)\n");
fprintf(stderr, "\t-i initial value (HEX) / -I initial value (DEC)\n");
fprintf(stderr, " example:\n");
fprintf(stderr, "\t%s -g 0x131 -i 0xff dallas-maxim.dat\n", prog);
fprintf(stderr, "\t%s -g 0x185 -i 0 x8+x7+x2+1.dat\n", prog);
}
int main(int argc, char *argv[])
{
FILE *fp;
int p, ini;
prog = *argv;
shift;
p = P;
ini = INI;
while ((argc > 0) && (argv[0][0] == '-') && (argv[0][1] != EOS)) {
if ((argc > 1) && (argv[0][1] == 'p')) {
shift;
p = strtol(*argv, (char **)NULL, 16) & 0xff;
}
else if ((argc > 1) && (argv[0][1] == 'P')) {
shift;
p = atoi(*argv) & 0xff;
}
else if ((argc > 1) && (argv[0][1] == 'g')) {
shift;
p = strtol(*argv, (char **)NULL, 16) & 0xff;
}
else if ((argc > 1) && (argv[0][1] == 'G')) {
shift;
p = atoi(*argv) & 0xff;
}
else if ((argc > 1) && (argv[0][1] == 'i')) {
shift;
ini = strtol(*argv, (char **)NULL, 16) & 0xff;
}
else if ((argc > 1) && (argv[0][1] == 'I')) {
shift;
ini = atoi(*argv) & 0xff;
}
else {
usage();
exit(1);
}
shift;
}
if (argc > 0) {
while (argc > 0) {
if ((argv[0][1] == '-') && (argv[0][1] == EOS)) {
fp = stdin;
}
else if ((fp = fopen(*argv, "r")) == NULL) {
fprintf(stderr, "%s: can't open %s\n", prog, *argv);
exit(1);
}
calc(fp, p, ini);
if (fp != stdin) {
fclose(fp);
}
shift;
}
}
else {
calc(stdin, p, ini);
}
exit(0);
}
/* Local Variables: */
/* compile-command:"cc -Wall -o crc8 crc8.c" */
/* End: */