用bitset进行2进制输入输出
C/C++内置的输入、输出,对整数进制只支持三种:8进制、10进制、16进制。记得很久以前,有好几次想用到2进制的输入输出,最终只好自已转换。
昨天kaikai突然发了一个POST:
kaikai:
看看能不能把这个程序改得更短?
![](/Images/OutliningIndicators/None.gif)
#include <cstdio>
int main()
{
char*a,b[33];
scanf("%*d");
while(scanf("%s",b)==1)
{
int d=0;
for(a=b;*a;)d=d*2|*a++%2;
printf("%d.%d.%d.%d\n",d>>24&255,d>>16&255,d>>8&255,d&255);
}
return 0;
}
一眼看过去,呵呵,输入输出不可省,核心还是二进制的转换问题。于是想起以前曾经做过的事情,学习多了,直觉的可以用bitset来实现。打开MSDN,查找bitset,嘿,果然有定义流输入操作符。
写了一个测试:
#include <iostream>
#include <bitset>
using namespace std;
![](/Images/OutliningIndicators/None.gif)
void main()
{
bitset<32> a;
cin >> a;
cout << a.to_ulong() << endl;
}
呵呵,搞定了,输入2进制,输出10进制,完全正常。以后输入2进制串的时候,就不需要自已转换了。
补充:
经过wang.lj 网友的提醒,才发现C库中还有一个函数,就是用来将数字串以指定的数制转换成整数的:
i = strtol(s, &end, 2); //二进制流转换为16进制字符串
昨天kaikai突然发了一个POST:
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](/Images/OutliningIndicators/None.gif)
写了一个测试:
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](/Images/OutliningIndicators/None.gif)
补充:
经过wang.lj 网友的提醒,才发现C库中还有一个函数,就是用来将数字串以指定的数制转换成整数的:
i = strtol(s, &end, 2); //二进制流转换为16进制字符串