#include<iostream>intmain(){intbin{};// assume 16-bit intsbin=0x0001;// assign binary 0000 0000 0000 0001 to the variablebin=0x0002;// assign binary 0000 0000 0000 0010 to the variablebin=0x0004;// assign binary 0000 0000 0000 0100 to the variablebin=0x0008;// assign binary 0000 0000 0000 1000 to the variablebin=0x0010;// assign binary 0000 0000 0001 0000 to the variablebin=0x0020;// assign binary 0000 0000 0010 0000 to the variablebin=0x0040;// assign binary 0000 0000 0100 0000 to the variablebin=0x0080;// assign binary 0000 0000 1000 0000 to the variablebin=0x00FF;// assign binary 0000 0000 1111 1111 to the variablebin=0x00B3;// assign binary 0000 0000 1011 0011 to the variablebin=0xF770;// assign binary 1111 0111 0111 0000 to the variablereturn0;}
在 C++14 中,可以使用0b前缀来创建二进制字面量:
1 2 3 4 5 6 7 8 9101112
#include<iostream>intmain(){intbin{};// assume 16-bit intsbin=0b1;// assign binary 0000 0000 0000 0001 to the variablebin=0b11;// assign binary 0000 0000 0000 0011 to the variablebin=0b1010;// assign binary 0000 0000 0000 1010 to the variablebin=0b11110000;// assign binary 0000 0000 1111 0000 to the variablereturn0;}
因为二进制字面量一旦长了就很难阅读,C++14引入了单引号'作为分隔符。
123456789
#include<iostream>intmain(){intbin{0b1011'0010};// assign binary 1011 0010 to the variablelongvalue{2'132'673'462};// much easier to read than 2132673462return0;}
如果你的编译器不支持 C++14,那么你使用上述表示法的时候将会报错。
此外,请注意分隔符不能放在第一位前面:
1
intbin{0b'1011'0010};// error: ' used before first digit of value