java|CRC32源码

CRC32源码 C语言版

static u32 CRC32[256]; static bool init = 0; //初始化表,在单片机等RAM较小的系统,可以在源码中把tab构造为const数组 static void init_table() { for (int i = 0; i < 256; i++) { u32 crc = i; for (int j = 0; j < 8; j++) { if (crc & 1) { crc = (crc >> 1) ^ 0xEDB88320; } else { crc = crc >> 1; } } CRC32[i] = crc; } }//crc32实现函数 u32 crc32(const u8* buf, int len) { u32 ret = 0xFFFFFFFF; if (!init) { init_table(); init = true; } for (int i = 0; i < len; i++) { ret = CRC32[((ret & 0xFF) ^ buf[i])] ^ (ret >> 8); } ret = ~ret; return ret; }


纯JAVA版
/** * 纯java实现的CRC32 * @author houj * */ public class Crc32 { static int[] CRC32 = new int[256]; static boolean init = false; /** * 初始化表 */ static void init_table() { for (int i = 0; i < 256; i++) { int crc = i; for (int j = 0; j < 8; j++) { if ((crc & 1) != 0) { crc = (crc >>> 1) ^ 0xEDB88320; } else { crc = crc >>> 1; } } CRC32[i] = crc; } }/** * crc32实现函数 * * @param buf * @param len * @return */ public static int crc32(byte[] buf, int len) { int ret = 0xFFFFFFFF; int i; if (!init) { init_table(); init = true; } for (i = 0; i < len; i++) { ret = CRC32[(((ret & 0xFF) ^ buf[i])) & 0xFF] ^ (ret >>> 8); } ret = ~ret; return ret; }/** * 测试 * * @param args */ public static void main(String[] args) { // 构造数据 byte[] bs = new byte[4096]; new java.util.Random().nextBytes(bs); //纯java实现 int r = crc32(bs, bs.length); System.out.println(r); //java原生实现 java.util.zip.CRC32 c3 = new java.util.zip.CRC32(); c3.reset(); c3.update(bs, 0, bs.length); int r2 = (int) c3.getValue(); System.out.println(r2); System.out.println("OK:"+(r==r2)); } }

【java|CRC32源码】转载于:https://my.oschina.net/u/184090/blog/338558

    推荐阅读