1

我想对 sum+ 中的任何位进行 1s 补码,并将补码的位保存在 finalsum 中。怎么做。我对使用 bitvec 和 uint32_t 类型的东西有点弱。所以我在这里很困惑。请帮忙。

#include <iostream>
#include <string>
#include <bitset>
using namespace std;
#include <vector>
#include <stdint.h>

int main() {
int i;
string j;

std::string message = "hello "; // Some string.
std::vector<uint16_t> bitvec;
unsigned char* cp = message.c_str()+1;
while (*cp) {
   uint16_t bits = *(cp-1)>>8 + *(cp);
   bitvec.push_back(bits);
}

uint32_t sum=0;
uint16_t overflow=0;

for(auto j = bitvec.begin(); j != bitvec.end(); ++j) { 
sum += *j;
std::uint16_t; overflow = sum>>16;  //capture the overflow bit, move it back to lsb
sum &= (1<<16)-1;    //clear the overflow
sum += overflow;     //add it back as lsb
}

uint32_t finalsum=0;
for (k=0; k<=sum.length(); k++)
{finalsum = !(sum[k])]
}

cout << finalsum ;
return 0;

}
4

1 回答 1

3

看起来您正在尝试实现诸如 TCP 的 1s 补码校验和之类的东西。

// Compute the sum.  Let overflows accumulate in upper 16 bits.
for(auto j = bitvec.begin(); j != bitvec.end(); ++j) 
    sum += *j;

// Now fold the overflows into the lower 16 bits.  This requires two folds, as the
// first fold may generate another carry.  This can't happen more than once though.
sum = (sum & 0xFFFF) + (sum >> 16);
sum = (sum & 0xFFFF) + (sum >> 16);

// Return the 1s complement sum in finalsum
finalsum = sum;

这应该可以解决问题。

另外,我认为您需要cp += 2在此循环中的某个地方:

while (*cp) {
    uint16_t bits = *(cp-1)>>8 + *(cp);
    bitvec.push_back(bits);
    cp += 2;  // advance to next pair of characters
}

如果您的输入字符串不是偶数个字符,该循环也将失败,因此请考虑更健壮地重写它...

于 2013-11-09T09:47:02.400 回答