Last active
August 29, 2015 14:03
-
-
Save brianloveswords/d250b75df8df21cee049 to your computer and use it in GitHub Desktop.
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
pub fn i64_as_bytes_be(n: i64) -> Vec<u8> { | |
let mut vec = Vec::with_capacity(8); | |
vec.push(((n & 0xff00000000000000) >> 56) as u8); | |
vec.push(((n & 0x00ff000000000000) >> 48) as u8); | |
vec.push(((n & 0x0000ff0000000000) >> 40) as u8); | |
vec.push(((n & 0x000000ff00000000) >> 32) as u8); | |
vec.push(((n & 0x00000000ff000000) >> 24) as u8); | |
vec.push(((n & 0x0000000000ff0000) >> 16) as u8); | |
vec.push(((n & 0x000000000000ff00) >> 8) as u8); | |
vec.push(((n & 0x00000000000000ff)) as u8); | |
vec | |
} | |
pub fn i64_as_bytes_le(n: i64) -> Vec<u8> { | |
let mut vec = Vec::with_capacity(8); | |
vec.push(((n & 0x00000000000000ff)) as u8); | |
vec.push(((n & 0x000000000000ff00) >> 8) as u8); | |
vec.push(((n & 0x0000000000ff0000) >> 16) as u8); | |
vec.push(((n & 0x00000000ff000000) >> 24) as u8); | |
vec.push(((n & 0x000000ff00000000) >> 32) as u8); | |
vec.push(((n & 0x0000ff0000000000) >> 40) as u8); | |
vec.push(((n & 0x00ff000000000000) >> 48) as u8); | |
vec.push(((n & 0xff00000000000000) >> 56) as u8); | |
vec | |
} | |
fn bytes_as_i64_be(n: &[u8]) -> i64 { | |
n[0] as i64 << 56 | |
| n[1] as i64 << 48 | |
| n[2] as i64 << 40 | |
| n[3] as i64 << 32 | |
| n[4] as i64 << 24 | |
| n[5] as i64 << 16 | |
| n[6] as i64 << 8 | |
| n[7] as i64 | |
} | |
fn bytes_as_i64_le(n: &[u8]) -> i64 { | |
n[7] as i64 << 56 | |
| n[6] as i64 << 48 | |
| n[5] as i64 << 40 | |
| n[4] as i64 << 32 | |
| n[3] as i64 << 24 | |
| n[2] as i64 << 16 | |
| n[1] as i64 << 8 | |
| n[0] as i64 | |
} | |
fn main() { | |
let n = 0x1122334455667788_i64; | |
let be_bytes = i64_as_bytes_be(n); | |
let le_bytes = i64_as_bytes_le(n); | |
println!("{}", n); | |
println!("{}", be_bytes); | |
println!("{}", le_bytes); | |
assert_eq!(n, bytes_as_i64_be(be_bytes.as_slice())); | |
assert_eq!(n, bytes_as_i64_le(le_bytes.as_slice())); | |
} |
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
1234605616436508552 | |
[17, 34, 51, 68, 85, 102, 119, 136] | |
[136, 119, 102, 85, 68, 51, 34, 17] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment