Created
June 21, 2017 17:14
Rust byte splitting
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
fn main() { | |
let byte: u8 = 0b1001_0110; | |
let mut high: u8 = 0b0000_0000; | |
let mut low: u8 = 0b0000_0000; | |
/* | |
(1 << 0) -> 0000 0001 | |
(1 << 1) -> 0000 0010 | |
(1 << 2) -> 0000 0100 | |
(1 << 3) -> 0000 1000 | |
(1 << 4) -> 0001 0000 | |
(1 << 5) -> 0010 0000 | |
(1 << 6) -> 0100 0000 | |
(1 << 7) -> 1000 0000 | |
*/ | |
//high | |
if byte & (1 << 4) == 0b0001_0000 { high = high | 1 << 0; } | |
if byte & (1 << 5) == 0b0010_0000 { high = high | 1 << 1; } | |
if byte & (1 << 6) == 0b0100_0000 { high = high | 1 << 2; } | |
if byte & (1 << 7) == 0b1000_0000 { high = high | 1 << 3; } | |
//low | |
if byte & (1 << 0) == 0b0000_0001 { low = low | 1 << 0; } | |
if byte & (1 << 1) == 0b0000_0010 { low = low | 1 << 1; } | |
if byte & (1 << 2) == 0b0000_0100 { low = low | 1 << 2; } | |
if byte & (1 << 3) == 0b0000_1000 { low = low | 1 << 3; } | |
println!("byte: {:08b}\nupper: {:04b}\nlower: {:04b}", byte, high, low); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment