Skip to content

Instantly share code, notes, and snippets.

@substack substack/bytes.js
Last active May 17, 2019

Embed
What would you like to do?
split a u64 into two u32s and verify that the combination works
var n = 123456789012345
var u32a = Uint32Array.from([n,n/2**32])
var u8a = new Uint8Array(u32a.buffer)
console.log(u8a)
// Uint8Array [ 121, 223, 13, 134, 72, 112, 0, 0 ]
let n = 123456789012345
let [low,high] = Uint32Array.from([n,n/2**32])
console.log("low=",low, "high=",high)
use std::env;
use failure::Error;
fn main () -> Result<(),Error> {
let args: Vec<String> = env::args().collect();
if args[1] == "split" {
let n = args[2].parse::<u64>()?;
let low = (n % (1 << 32)) as u32;
let high = (n >> 32) as u32;
println!["{} {}", low, high];
} else if args[1] == "join" {
let low = args[2].parse::<u32>()?;
let high = args[3].parse::<u32>()?;
let mut data: Vec<u8> = vec![];
data.extend_from_slice(&low.to_le_bytes());
data.extend_from_slice(&high.to_le_bytes());
let res = u64::from_le_bytes([
data[0], data[1], data[2], data[3],
data[4], data[5], data[6], data[7]
]);
println!["{}", res];
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.