我可以使用二进制字面C或C ++? [英] Can I use a binary literal in C or C++?
问题描述
我需要一个二进制数来工作。
I need to work with a binary number.
我试着写:
const x = 00010000;
但它没有工作。
我知道我可以使用具有相同的值作为一个十六进制数 00010000
,但我想知道如果有一个二进制数,如果C ++中的类型没有,有没有我的问题的另一个解决方案?
I know that I can use an hexadecimal number that has the same value as 00010000
, but I want to know if there is a type in C++ for binary numbers and if there isn't, is there another solution for my problem?
推荐答案
可以的使用 BOOST_BINARY
等待的C ++ 0x。 :) BOOST_BINARY
可以说是拥有超过模板实现一个优势,因为它的可以在C程序中使用,以及(它是100%preprocessor驱动的。)
You can use BOOST_BINARY
while waiting for C++0x. :) BOOST_BINARY
arguably has an advantage over template implementation insofar as it can be used in C programs as well (it is 100% preprocessor-driven.)
要做到相反(即打印出二进制形式的数字),则可以使用非便携式 itoa
功能,或实现自己的。
To do the converse (i.e. print out a number in binary form), you can use the non-portable itoa
function, or implement your own.
不幸的是你不能做基地2 STL格式数据流(因为 setbase
只会荣誉基地8,10和16),但你的可以的使用一个的std ::字符串
itoa
,或(更简洁,但稍微低效率)和std :: bitset
。
Unfortunately you cannot do base 2 formatting with STL streams (since setbase
will only honour bases 8, 10 and 16), but you can use either a std::string
version of itoa
, or (the more concise, yet marginally less efficient) std::bitset
.
的(谢谢你的位集$ C $ 罗杰 C>提示!)
的
#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
另请阅读香草萨特的的 庄园农场 的的一个有趣的讨论弦乐格式化程序
Also read Herb Sutter's The String Formatters of Manor Farm for an interesting discussion.
这篇关于我可以使用二进制字面C或C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!