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

我试着写:

const char x = 00010000;

但这并没有起作用。

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


当前回答

下面是我的函数没有添加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;
}

其他回答

你也可以像这样使用内联汇编:

int i;

__asm {
    mov eax, 00000000000000000000000000000000b
    mov i,   eax
}

std::cout << i;

好吧,这可能有点过分,但确实有效。

二进制数的“类型”与任何十进制、十六进制或八进制数相同:int(甚至char, short, long long)。

当你给一个常数赋值时,你不能用11011011赋值(奇怪而不幸的是),但你可以使用hex。海克斯更容易从心理上理解。块在啃(4位)和翻译成一个字符在[0-9a-f]。

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++中获得最多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。

你可以使用bitset

bitset<8> b(string("00010000"));
int i = (int)(bs.to_ulong());
cout<<i;