gpt4 book ai didi

c++ - 简单的运算符(operator)+问题躲避我

转载 作者:太空宇宙 更新时间:2023-11-04 15:09:01 25 4
gpt4 key购买 nike

我试图添加两个 uint8_t 列表,就好像列表是单独的整数一样,我得到了一些奇怪的值:

0x1000 + 0x100 + 0x10 -> 0x1210 ??????

代码如下:

// values 0x123456 stored as: {12, 34, 56}
integer operator+(integer rhs){
// internal list called 'value'
std::list <uint8_t> top = value, bottom = rhs.value;
if (value.size() < rhs.value.size())
top.swap(bottom);
top.push_front(0); // extra byte for carrying over
while (bottom.size() + 1 < top.size()) // match up the byte sizes, other than the carry over
bottom.push_front(0);
bool carry = false, next_carry = false;
for(std::list <uint8_t>::reverse_iterator i = top.rbegin(), j = bottom.rbegin(); j != bottom.rend(); i++, j++){
next_carry = (((uint8_t) (*i + *j + carry)) <= std::min(*i, *j));
*i += *j + carry;
carry = next_carry;
}
if (carry)
*top.begin() = 1;
return integer(top);
}

谁能告诉我我做错了什么?

最佳答案

在您的示例 ( 0x100 + 0x10 ) 中,您以 carry = false 开头, *top.rbegin() = 0 , 和 *bottom.rbegin() = 0 .当我们进入循环时,我们会看到以下测试:

next_carry = (((uint8_t) (*i + *j + carry)) <= std::min(*i, *j));
// given *i == 0, *j == 0, and carry == false
// this will evaluate to TRUE

next_carry滚动到下一个添加,您最终得到 carry = true , 当它应该是 false . 将条件切换为 < std::min(*i, *j) .

关于c++ - 简单的运算符(operator)+问题躲避我,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6486085/

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