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

我试着写:

const char x = 00010000;

但这并没有起作用。

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


当前回答

这篇文章可能会有所帮助。

/* Helper macros */
#define HEX__(n) 0x##n##LU
#define B8__(x) ((x&0x0000000FLU)?1:0) \
+((x&0x000000F0LU)?2:0) \
+((x&0x00000F00LU)?4:0) \
+((x&0x0000F000LU)?8:0) \
+((x&0x000F0000LU)?16:0) \
+((x&0x00F00000LU)?32:0) \
+((x&0x0F000000LU)?64:0) \
+((x&0xF0000000LU)?128:0)

/* User macros */
#define B8(d) ((unsigned char)B8__(HEX__(d)))
#define B16(dmsb,dlsb) (((unsigned short)B8(dmsb)<<8) \
+ B8(dlsb))
#define B32(dmsb,db2,db3,dlsb) (((unsigned long)B8(dmsb)<<24) \
+ ((unsigned long)B8(db2)<<16) \
+ ((unsigned long)B8(db3)<<8) \
+ B8(dlsb))


#include <stdio.h>

int main(void)
{
    // 261, evaluated at compile-time
    unsigned const number = B16(00000001,00000101);

    printf("%d \n", number);
    return 0;
}

它的工作原理!(所有的功劳都归于汤姆·托夫斯。)

其他回答

C语言没有用于纯二进制数的原生表示法。这里最好是八进制(例如07777)或十六进制(例如0xfff)。

您可以使用的最小单位是字节(char类型)。您可以使用位操作符来处理位。

至于整数字面值,您只能使用十进制(以10为基数)、八进制(以8为基数)或十六进制(以16为基数)数字。在C和c++中没有二进制(以2为基数)字面值。

八进制数前缀为0,十六进制数前缀为0x。十进制数没有前缀。

在c++ 0x中,你可以通过用户定义的文字来做你想做的事情。

你可以使用这个问题中的函数在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;

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