async_modbus/util.rs
1/// CRC for Modbus RTU messages.
2pub const fn crc(data: &[u8]) -> u16 {
3 let mut crc = 0xffff;
4 let mut i = 0;
5
6 while i < data.len() {
7 crc ^= data[i] as u16;
8 let mut j = 0;
9 while j < 8 {
10 if (crc & 0x0001) != 0 {
11 crc >>= 1;
12 crc ^= 0xa001;
13 } else {
14 crc >>= 1;
15 }
16
17 j += 1;
18 }
19
20 i += 1;
21 }
22
23 crc
24}
25
26#[cfg(test)]
27mod tests {
28 use hex_literal::hex;
29
30 #[test]
31 fn crc() {
32 assert_eq!(super::crc(&hex!("00 06 00 00 00 17")), 0x15c8);
33 }
34}