Arrays 向存储为字节数组的整数添加值
在将数组视为单个整数的情况下,向字节数组添加(而不是追加)值的最佳方法是什么 例如:Arrays 向存储为字节数组的整数添加值,arrays,byte,rust,Arrays,Byte,Rust,在将数组视为单个整数的情况下,向字节数组添加(而不是追加)值的最佳方法是什么 例如: let arr = [0xFF, 0x01, 0xC3, 0x43]; 假设arr可以是任意长度。例如,如果我将350添加到这个数组中,那么新数组应该是:[0xFF,0x01,0xC4,0xA1]。我提出的解决方案只有当我们递增1时才有效,因此我需要在循环中调用该方法amount次,如果amount较大,这可能会降低效率(本例使用Vec,而不是数组): fn增量字节向量(vec:vec)->vec{ 让mut
let arr = [0xFF, 0x01, 0xC3, 0x43];
假设arr
可以是任意长度。例如,如果我将350添加到这个数组中,那么新数组应该是:[0xFF,0x01,0xC4,0xA1]
。我提出的解决方案只有当我们递增1时才有效,因此我需要在循环中调用该方法amount
次,如果amount
较大,这可能会降低效率(本例使用Vec
,而不是数组):
fn增量字节向量(vec:vec)->vec{
让mut done=false;
向量iter().rev().map(|和v |{
如果完成{
v
}如果v==0xFF,则为else{
0
}否则{
完成=正确;
v+1
}
}).rev().collect::()
}
我如何调整上述内容,以便函数可以采用
数量
参数?您基本上是在以256为基数实现sum。解决这个问题的一种方法是将其转换为十进制,再加上350,然后将结果重新转换为以256为基数
也就是说,[0xFF,0x01,0xC3,0x43]
是:
255 (FF) * 256^3 +
1 * 256^2 +
195 (C3) * 256^1 +
67 (43) * 256^0 = 4,278,305,603 (base10)
4,278,305,603 + 350 = 4_278_305_953
现在您需要将其重新转换为基数256。最后一个钻头在生锈时可能看起来像这样:
// warning, does not handle overflows
fn base10_to_256(n: u64) -> [u8; 4] {
let mut converted_number = [0u8; 4];
let mut number_to_convert = n;
let base = 256u64;
for index in 0.. {
converted_number[3-index] = (number_to_convert % base) as u8;
number_to_convert = number_to_convert / base;
if number_to_convert == 0 { break; }
}
converted_number
}
这里没什么好说的;只需将矢量相加,从后向前 这个数字可能会溢出。我选择了返回携带;您可能更喜欢扩展向量。我的解决方案使用变异,因为它比分配一个新的向量更有效,而且因为我没有改变长度,所以我认为在一个可变的切片上使用泛型更好
/// 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);
}
请注意“假设
arr
可以是任意长度。”问题的一部分。哦,我很惊讶作为u8
的金额不被视为溢出;我希望在铸造之前,Rust会要求模是明确的。你知道这会不会继续下去,还是应该提防将来添加的溢出检查?@MatthieuM。
/// 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);
}