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

我试着写:

const char x = 00010000;

但这并没有起作用。

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


当前回答

c++的过度工程思维已经在这里的其他答案中得到了很好的解释。以下是我尝试用C,保持简单的心态来做这件事:

unsigned char x = 0xF; // binary: 00001111

其他回答

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语言没有用于纯二进制数的原生表示法。这里最好是八进制(例如07777)或十六进制(例如0xfff)。

你可以使用这个问题中的函数在c++中获得最多22位。下面是经过适当编辑的链接代码:

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

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

所以你可以这样做binary<0101011011>::value。

用法:二进制(00010001);

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

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

return b;

}

下面是我的函数没有添加Boost库:

用法:BOOST_BINARY(00010001);

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