我需要使用一个二进制数。
我试着写:
const x = 00010000;
但这没有用。
我知道我可以使用与值相同的十六进制数00010000
,但是我想知道C ++中是否存在用于二进制数的类型,如果没有,那么是否存在针对我的问题的另一种解决方案?
您可以使用BOOST_BINARY
在等待的C ++ 0x。:)BOOST_BINARY
在模板实现方面具有优势,因为它也可以在C程序中使用(它是100%预处理程序驱动的)。
要进行相反的处理(即以二进制形式打印数字),可以使用非便携式itoa
函数,也可以实现自己的。
不幸的是,您不能使用STL流进行base 2格式化(因为setbase
将仅支持base 8、10和16),但是您可以使用或的std::string
版本itoa
(更为简洁,但效率稍低)std::bitset
。
#include <boost/utility/binary.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <bitset>
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
unsigned short b = BOOST_BINARY( 10010 );
char buf[sizeof(b)*8+1];
printf("hex: %04x, dec: %u, oct: %06o, bin: %16s\n", b, b, b, itoa(b, buf, 2));
cout << setfill('0') <<
"hex: " << hex << setw(4) << b << ", " <<
"dec: " << dec << b << ", " <<
"oct: " << oct << setw(6) << b << ", " <<
"bin: " << bitset< 16 >(b) << endl;
return 0;
}
产生:
hex: 0012, dec: 18, oct: 000022, bin: 10010
hex: 0012, dec: 18, oct: 000022, bin: 0000000000010010
另请阅读Herb Sutter的“庄园农场的弦乐格式化者”,以进行有趣的讨论。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句