将值添加(而不是附加)到字节数组的最佳方法是什么,其中该数组被视为单个整数?
例如:
let arr = [0xFF, 0x01, 0xC3, 0x43];
Run Code Online (Sandbox Code Playgroud)
假设arr可以是任意长度。例如,如果我将 350 添加到其中,则新数组应该是:[0xFF, 0x01, 0xC4, 0xA1]。我提出的解决方案仅在我们递增 1 时才有效,因此我需要在循环amount时间内调用该方法,这对于大的amount's可能效率低下(本示例使用Vec's 而不是数组):
fn increment_byte_vec(vec: Vec<u8>) -> Vec<u8> {
let mut done = false;
vec.iter().rev().map(|&v| {
if done {
v
} else if v == 0xFF {
0
} else {
done = true;
v + 1
}
}).rev().collect::<Vec<_>>()
}
Run Code Online (Sandbox Code Playgroud)
我将如何调整上述内容以便函数可以接受amount参数?
这里不多说;只需添加并携带向量,回到前面。
数字有可能溢出。我选择退还carry;您可能更喜欢扩展向量。我的解决方案使用了变异,因为它比分配一个新向量更有效,而且由于我没有改变长度,我认为在可变切片上通用更好。
/// Increments the bytes, assuming the most significant
/// bit is first, and returns the carry.
fn increment_bytes(b256: &mut [u8], mut amount: u64) -> u64 {
let mut i = b256.len() - 1;
while amount > 0 {
amount += b256[i] as u64;
b256[i] = amount as u8;
amount /= 256;
if i == 0 { break; }
i -= 1;
}
amount
}
fn main() {
let mut input = vec![0xFF, 0x01, 0xC3, 0x43];
println!("{}", increment_bytes(&mut input, 350));
println!("{:?}", input);
}
Run Code Online (Sandbox Code Playgroud)