Created
June 23, 2017 15:35
-
-
Save lborg019/e080cad20ab401e5bf7a0d5751903bd5 to your computer and use it in GitHub Desktop.
Permuting bits using bitshifts can be at least 20 times faster than using String operations (in nanos)
This file contains hidden or 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
use std::time::{Instant}; | |
fn permute_eight_bits(ten_bit: u16) -> u8 | |
{ | |
// P8[6 3 7 4 8 5 10 9] | |
// P8[5 2 6 3 7 4 9 8] (-1) | |
let mut permuted_byte = 0b0000_0000_0000_0000; | |
let p_eight: [(u16,u16);8] = [(5, 0b0000_0000_0010_0000), | |
(2, 0b0000_0000_0000_0100), | |
(6, 0b0000_0000_0100_0000), | |
(3, 0b0000_0000_0000_1000), | |
(7, 0b0000_0000_1000_0000), | |
(4, 0b0000_0000_0001_0000), | |
(9, 0b0000_0010_0000_0000), | |
(8, 0b0000_0001_0000_0000)]; | |
for x in 0..8 { | |
permuted_byte = permuted_byte << 1; | |
if ten_bit & (1 << p_eight[x].0) == p_eight[x].1 { | |
permuted_byte = permuted_byte | 1; | |
} | |
} | |
permuted_byte | |
} | |
fn permute_eight_str(ten_bit: u16) -> String | |
{ | |
let init_key_str = format!("{:010b}", ten_bit); | |
let mut permuted_chars: Vec<char> = Vec::new(); | |
let mut permuted_string = String::with_capacity(8); | |
let p_eight: [usize;8] = [6,3,7,4,8,5,10,9]; | |
for x in 0..8 { | |
permuted_chars.push(init_key_str.chars().nth(p_eight[x]-1).unwrap() as char); | |
} | |
for c in &permuted_chars // to avoid 'move' errors, we pass a reference | |
{ // as '&permuted_chars' and dereference '*c' | |
permuted_string.push(*c); | |
} | |
permuted_string | |
} | |
fn main() { | |
let bits = 0b0000_1111_0000_1111; | |
//call permutation using Strings | |
let mut now = Instant::now(); | |
let string_result = permute_eight_str(bits); | |
let mut new_now = Instant::now(); | |
let delta = new_now.duration_since(now); | |
//call permutation using Bitshifts | |
now = Instant::now(); | |
let bits_result = permute_eight_bits(bits); | |
new_now = Instant::now(); | |
let delta_two = new_now.duration_since(now); | |
println!("str: {:?}, took: {:?}", string_result, delta); | |
println!("bits: {:08b}, took: {:?}", bits_result, delta_two); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment