Created
April 18, 2016 09:11
-
-
Save SPY/e139f5de91dd93b6ff626b4bf8de1b7f to your computer and use it in GitHub Desktop.
Convert Rust u8 slice to i32
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 slice_to_i32_be(data: &[u8]) -> i32 { | |
assert!(data.len() >= 4); | |
let first = data[0]; | |
let sign = if first & 0x80 != 0 { -1 } else { 1 }; | |
sign * ( | |
(((first & 0x7F) as i32) << 24) + | |
((data[1] as i32) << 16) + | |
((data[2] as i32) << 8 ) + | |
( data[3] as i32 ) | |
) | |
} | |
fn slice_to_i32_le(data: &[u8]) -> i32 { | |
assert!(data.len() >= 4); | |
let first = data[3]; | |
let sign = if first & 0x80 != 0 { -1 } else { 1 }; | |
sign * ( | |
(((first & 0x7F) as i32) << 24) + | |
((data[2] as i32) << 16) + | |
((data[1] as i32) << 8 ) + | |
( data[0] as i32 ) | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment