我需要处理一个二进制数。

我试着写:

const char x = 00010000;

但这并没有起作用。

我知道我可以使用与00010000值相同的十六进制数,但我想知道在c++中是否有用于二进制数的类型,如果没有,是否有其他解决方案?


当前回答

template<unsigned long N>
struct bin {
    enum { value = (N%10)+2*bin<N/10>::value };
} ;

template<>
struct bin<0> {
    enum { value = 0 };
} ;

// ...
    std::cout << bin<1000>::value << '\n';

字面值最左边的数字仍然是1,但不管怎样。

其他回答

您可以在等待c++ 0x时使用BOOST_BINARY。BOOST_BINARY可以说比模板实现更有优势,因为它也可以在C程序中使用(它是100%预处理器驱动的)。

要做相反的事情(即以二进制形式打印一个数字),您可以使用不可移植的itoa函数,或者实现自己的函数。

不幸的是,你不能对STL流进行2进制格式化(因为setbase只支持8、10和16进制),但你可以使用itoa的std::string版本,或者(更简洁,但效率略低)std::bitset。

#include <boost/utility/binary.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <bitset>
#include <iostream>
#include <iomanip>

using namespace std;

int main() {
  unsigned short b = BOOST_BINARY( 10010 );
  char buf[sizeof(b)*8+1];
  printf("hex: %04x, dec: %u, oct: %06o, bin: %16s\n", b, b, b, itoa(b, buf, 2));
  cout << setfill('0') <<
    "hex: " << hex << setw(4) << b << ", " <<
    "dec: " << dec << b << ", " <<
    "oct: " << oct << setw(6) << b << ", " <<
    "bin: " << bitset< 16 >(b) << endl;
  return 0;
}

生产:

hex: 0012, dec: 18, oct: 000022, bin:            10010
hex: 0012, dec: 18, oct: 000022, bin: 0000000000010010

也可以阅读Herb Sutter的《The String Formatters of Manor Farm》,了解有趣的讨论。

template<unsigned long N>
struct bin {
    enum { value = (N%10)+2*bin<N/10>::value };
} ;

template<>
struct bin<0> {
    enum { value = 0 };
} ;

// ...
    std::cout << bin<1000>::value << '\n';

字面值最左边的数字仍然是1,但不管怎样。

从c++ 14开始,你可以使用二进制字面值,现在它们是语言的一部分:

unsigned char a = 0b00110011;

只需使用c++中的标准库:

#include <bitset>

你需要一个std::bitset类型的变量:

std::bitset<8ul> x;
x = std::bitset<8>(10);
for (int i = x.size() - 1; i >= 0; i--) {
      std::cout << x[i];
}

在本例中,我将10的二进制形式存储在x中。

8ul定义了位的大小,所以7ul意味着7位等等。

用法:二进制(00010001);

int二进制(int a){ Int b = 0;

for (int i = 0;i < 8;i++){
    b += a % 10 << i;
    a = a / 10;
}

return b;

}