Created
January 19, 2024 05:42
-
-
Save kujirahand/ac35de4ec32a1fc11b0c3304c9a1bd19 to your computer and use it in GitHub Desktop.
CRC-32を計算する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
// CRC-32を計算する関数 | |
fn crc32(bin_data: &[u8]) -> u32 { | |
let crc32poly:u32 = 0xEDB88320; | |
// CRC-32の初期値 --- (*1) | |
let mut crc:u32 = 0xFFFFFFFF; | |
// バイト列の各バイトについて繰り返し計算を行う --- (*2) | |
for byte in bin_data { | |
// XORを行う --- (*3) | |
crc ^= *byte as u32; | |
// 8回(8ビット分)繰り返す --- (*4) | |
for _ in 0..8 { | |
// ただし下位ビットが1ならXORする --- (*5) | |
if (crc & 1) == 1 { | |
crc >>= 1; | |
crc ^= crc32poly; | |
} else { | |
crc >>= 1; | |
} | |
} | |
} | |
// ビットを反転させる --- (*6) | |
crc ^ 0xFFFFFFFF | |
} | |
fn main() { | |
// b"hello"のCRC-32を計算する --- (*7) | |
let bin_data = b"hello"; | |
let crc = crc32(bin_data); | |
println!("CRC-32: {:08X}", crc); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment