每四位二进制串一组,计算对应的十进制数是多少如何实现?

CharlesYJ 2012-02-29 11:17:19
各位好!

我有个文件里面存放着一个二进制的串,形如:10010001……

我现在想把它读进来,该用什么类型的格式读进来合适?

然后我要每四位一组计算它对应的十进制数是多少,如前面提到的,1001 0001

最后统计每个十进制数出现的次数,

请问如何实现比较简单有效?

谢谢!
...全文
202 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
CharlesYJ 2012-03-05
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 kuyucman 的回复:]

写了个大概,参考下吧:


C/C++ code

#include <string>
#include <vector>

using std::string;
using std::vector;


int Binary2Int(const string & item);

int main()
{
//4bit一组。
const int nItemSi……
[/Quote]

谢谢热心回复,最后我用C中的 位域 解决了哈!
东莞某某某 2012-03-04
  • 打赏
  • 举报
回复
写了个大概,参考下吧:



#include <string>
#include <vector>

using std::string;
using std::vector;


int Binary2Int(const string & item);

int main()
{
//4bit一组。
const int nItemSize = 4;

//读文件->strData
string strData("01100001010010101010");


string item;
vector<int> vcInteger;
for (string::size_type i=0; i<strData.size(); i+=nItemSize)
{
item = strData.substr(i,nItemSize);
vcInteger.push_back(Binary2Int(item));
}

//接下来解析vcInteger,计算数字出现的个数。 有了这个vcInteger,解析很简单
// ...

return 0;
}


int Binary2Int(const string & item)
{
int targ = 0;

//注意平台的大小端问题
targ += (item[3]=='1' ? 1 : 0);
targ += (item[2]=='1' ? 2 : 0);
targ += (item[1]=='1' ? 4 : 0);
targ += (item[0]=='1' ? 8 : 0);

return targ;
}
CharlesYJ 2012-03-04
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 xiyoulaoyuanjia 的回复:]

刚闲了会帮你写了个。。。

C/C++ code
void example(){

struct read_type{
char str[4];

}readI0;


FILE * fp;
if((fp=fopen("d:\\1.txt","r"))==NULL)
{
printf("……
[/Quote]

可是我是要按位读进来,你一次读进来四个字节?这不行吧,我是要一次读进来四个bit...求教!
xiyoulaoyuanjia 2012-02-29
  • 打赏
  • 举报
回复
刚闲了会帮你写了个。。。

void example(){

struct read_type{
char str[4];

}readI0;


FILE * fp;
if((fp=fopen("d:\\1.txt","r"))==NULL)
{
printf("cant open the file");
exit(0);
}
int a[16]={0}; //够用了
while(fread(&readI0,sizeof(struct read_type),1,fp)){

// cout<<readI0.str[0];
// cout<<readI0.str[1];
// cout<<readI0.str[2];
// cout<<readI0.str[3];

// 转化为十进制 最大1111为15
int b=(readI0.str[0]-48)*2*2*2+(readI0.str[1]-48)*2*2+(readI0.str[2]-48)*2+(readI0.str[3]-48);
cout<<b<<endl;
a[b]++;
}



}

64,439

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧