Created
October 3, 2016 14:23
-
-
Save zzeroo/2b9735eed64cd1b6f1cb3da70e0f9916 to your computer and use it in GitHub Desktop.
CRC-16 Implementation in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// rustc crc16.rs && ./crc16 2 7 # ./crc16 0x2 0x7 # geht auch .oO | |
use std::env; | |
use std::mem; | |
// CRC-16 Funktion nach dem Modbus Standard http://www.modbus.org/docs/Modbus_over_serial_line_V1_02.pdf | |
// Seite 39ff | |
fn crc16(message: Vec<u8>) -> u16 { | |
// Zum Start wird der CRC Buffer mit Einsen gefüllt | |
let mut crc = 0xFFFF; | |
// Dann wird jedes Byte des übergebenen Arrays (Vector in Rust genant) durchlaufen | |
for byte in message.iter() { | |
// Das erste Byte wird mit den ersten 8 Bit des CRC Buffers XOR'ed | |
crc ^= *byte as u16; | |
// Dann wird jedes einzellne Bit XOR'ed | |
for _i in (1..9).rev() { | |
if crc & 0x001 != 0 { | |
crc >>= 1; | |
crc ^= 0xA001; | |
} else { | |
crc >>= 1; | |
} | |
} | |
} | |
crc | |
} | |
fn main() { | |
let args: Vec<_> = env::args().collect(); | |
if args.len() < 2 { | |
println!("Usage: {}", args[0]); | |
return | |
} | |
// Überspringe den ersten Parameter (Name des Programms) und | |
// wandle die einzelen Strings im Array in u8 (unsigned int 8bit) | |
let message: Vec<u8> = args.iter().skip(1).map(|i| { | |
i.parse::<u8>().unwrap() | |
}).collect(); | |
// CRC-16 berechnen und Ergebnis der Variablen crc zuweisen | |
let crc = crc16(message); | |
// Ergebis ausgeben. Einmal in Hex Sschreibweise und als normaler Integer | |
println!("crc16 ist 0x{:X} ({})", crc, crc); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment