我只是尝试在C++中使用~运算符进行按位补码:
例如:
NOT 0101
--------
1010因此,在下面的代码中,我希望得到1010,但我得到的是负数。尽管我用unsigned类型定义了值,但怎么可能呢?
#include <iostream>
#include <stdio.h>
#include <string>
#include <bitset>
using namespace std;
int tob(int num) {
if (num == 0)
return 0;
return (num % 2) + 10*tob(num/2);
}
long unsigned int tol(string st) {
long unsigned int num = bitset<100>(st).to_ulong();
return num;
}
int main()
{
unsigned int x = tol("0101");
unsigned int z = ~x;
printf("%10d (decimal %u)\n", tob(z), z);
// -110 (decimal -6)
cout << tob(z) << endl; // -110
cout << z << endl; // -110
}我如何从1010获得not 0101 in C++?
谢谢!
发布于 2015-08-25 20:56:58
…如何从C++中的非0101获得1010?
使用std::位集表示四个位。
std::bitset<4> x("0101");
auto z = ~x;
std::cout << '~' << x << '=' << z << std::endl;Coliru实例
https://stackoverflow.com/questions/32213775
复制相似问题