gpt4 book ai didi

arrays - 将值添加到存储为字节数组的整数

转载 作者:行者123 更新时间:2023-11-29 08:05:25 25 4
gpt4 key购买 nike

将值添加(而不是追加)到字节数组(其中该数组被视为单个整数)的最佳方法是什么?

例如:

let arr = [0xFF, 0x01, 0xC3, 0x43];

假设 arr 可以是任意长度。例如,如果我向其添加 350,则新数组应为:[0xFF, 0x01, 0xC4, 0xA1]。我想出的解决方案只有在我们递增 1 时才有效,因此我需要在循环中调用该方法 amount 次,这对于较大的 amount 来说效率很低 的(此示例使用 Vec 而不是数组):

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<_>>()
}

我将如何调整上述内容以便该函数可以采用 amount 参数?

最佳答案

这里不多说;只需添加并携带向量,从后往前。

数字可能会溢出。我选择返回;您可能更愿意扩展向量。我的解决方案使用变异,因为它比分配新向量更有效,而且由于我没有改变长度,我认为在可变切片上通用化更好。

/// 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);
}

关于arrays - 将值添加到存储为字节数组的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34545347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com