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

我试着写:

const char x = 00010000;

但这并没有起作用。

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


当前回答

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

int i;

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

std::cout << i;

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

其他回答

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

/* 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;
}

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

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

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

我提出我的解决方案:

    #define B(x)                \
       ((((x) >>  0) & 0x01)    \
      | (((x) >>  2) & 0x02)    \
      | (((x) >>  4) & 0x04)    \
      | (((x) >>  6) & 0x08)    \
      | (((x) >>  8) & 0x10)    \
      | (((x) >> 10) & 0x20)    \
      | (((x) >> 12) & 0x40)    \
      | (((x) >> 14) & 0x80))

const uint8 font6[] = {
    B(00001110),    //[00]
    B(00010001),
    B(00000001),
    B(00000010),
    B(00000100),
    B(00000000),
    B(00000100),
    B(00000000),

我用这种方式定义了8位字体和图形,但也可以使用更宽的字体。宏B可以定义为生成0b格式,如果编译器支持的话。 操作:将二进制数解释为八进制,然后将位掩码并一起移位。中间值受到编译器可以处理的最大整数的限制,我猜64位应该可以。

它完全由编译器处理,不需要运行时代码。

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

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

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

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

你可以使用bitset

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