歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux綜合 >> Linux內核 >> Linux內核中crc16_table與crc32_table的計算

Linux內核中crc16_table與crc32_table的計算

日期:2017/2/28 16:01:59   编辑:Linux內核

CRC: Cyclic redundancy check 循環冗余校驗

內核中使用的crc16計算方法位於代碼樹/lib/crc16.c文件中

crc32的計算方法位於代碼樹/lib/crc32.c文件中

均采用了查表法

其中crc32的表由代碼樹/lib/gen_crc32table.c中的主機小程序計算而來

生成的冗余表保存在文件/lib/crc32table.h中

具體的計算方法可以參考gen_crc32table.c中的代碼

/lib/crc16.c中的crc16_table是直接定義的,沒有提供計算代碼

在學習了wiki上介紹的原理後,參考內核中crc32的計算方法,寫了個crc16的代碼

生成crc16_table表

  1. /*
  2. * crc16gen.c - CRC-16 table gen routine
  3. *
  4. * Generate the standard CRC-16 table:
  5. * Width 16
  6. * Poly 0x8005 (x^16 + x^15 + x^2 + 1)
  7. * Init 0
  8. *
  9. * <kernel.digger@gmail.com>
  10. *
  11. * This source code is licensed under the GNU General Public License,
  12. * Version 2. See the file COPYING for more details.
  13. */
  14. #include <stdio.h>
  15. #include <string.h>
  16. #define CRC_BITS 8
  17. #define TABLE_SIZE (1 << CRC_BITS)
  18. /* 在小端序機器上,因為低位在前,所以將多項式對應的位串反轉 */
  19. #define CRC16POLY_LE 0xa001
  20. #define CRC16POLY_BE 0x8005
  21. #define MASK_LE 0x0001
  22. #define MASK_BE 0x8000
  23. unsigned short crc16_table[TABLE_SIZE];
  24. /*
  25. * 在小端序的機器上,低位在前
  26. * 作為位串計算時,這裡的位操作向右移
  27. */
  28. static void
  29. crc16init_le(void)
  30. {
  31. unsigned short i, j, crc;
  32. for (i = 0; i < TABLE_SIZE; i++)
  33. {
  34. /* i為0-255的字符值,放在crc的低字節處 */
  35. crc = i;
  36. for (j = 0; j < CRC_BITS; j++)
  37. {
  38. /* 位串首位為1的話(最低bit為1)
  39. 則右移1位的同時異或多項式
  40. 否則異或0,即直接右移1位 */
  41. crc = (crc >> 1) ^ ((crc & MASK_LE) ? CRC16POLY_LE : 0);
  42. }
  43. crc16_table[i] = crc;
  44. }
  45. }
  46. static void
  47. crc16init_be(void)
  48. {
  49. unsigned short i, j, crc;
  50. for (i = 0; i < TABLE_SIZE; i++)
  51. {
  52. crc = i << 8;
  53. for (j = 0; j < CRC_BITS; j++)
  54. {
  55. crc = (crc << 1) ^ ((crc & MASK_BE) ? CRC16POLY_BE : 0);
  56. }
  57. crc16_table[i] = crc;
  58. }
  59. }
  60. static void
  61. crc16_print(void)
  62. {
  63. int i;
  64. for (i = 0; i < TABLE_SIZE; i++)
  65. {
  66. printf(" 0x%04x ", crc16_table[i]);
  67. if ((i % 8) == 7) {
  68. printf("\n");
  69. }
  70. }
  71. }
  72. void
  73. main(void)
  74. {
  75. crc16init_le();
  76. printf("--------------\nle table\n\n");
  77. crc16_print();
  78. crc16init_be();
  79. printf("--------------\nbe table\n\n");
  80. crc16_print();
  81. }

Copyright © Linux教程網 All Rights Reserved