问题描述
我需要处理一个二进制数.
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?
推荐答案
您可以在等待 C++0x 时使用 BOOST_BINARY
.:) BOOST_BINARY
可以说比模板实现有优势,因为它也可以在 C 程序中使用(它是 100% 预处理器驱动的.)
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.
不幸的是,您不能使用 STL 流进行 base 2 格式化(因为 setbase
仅支持 8、10 和 16 基数),但您可以使用 itoa 的
,或者(更简洁但效率稍低)std::string
版本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
.
#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
", 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 的庄园农场的字符串格式化程序 进行有趣的讨论.
Also read Herb Sutter's The String Formatters of Manor Farm for an interesting discussion.
这篇关于我可以在 C 或 C++ 中使用二进制文字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!