+ -
当前位置:首页 → 问答吧 → 怎样向文件一位一位的写入?或将01序列的字符串转换为二进制中位

怎样向文件一位一位的写入?或将01序列的字符串转换为二进制中位

时间:2011-12-12

来源:互联网

我现在有一大串01序列的字符串。C风格的。

怎样将他们变成二进制后写入文件。

比如“00000000000000000000000000000000000000001”对应int 型1的位,怎样将他们写入文件。

比如01字符序列(C风格字符串)中每32个字符转化为4字节int 数据后写入文件。

原始字符串中每个0,1占一个字节(8位),我想要每个0或1只占一位。

怎样才能做到呢?
涉及到文件IO,所以要高效。

作者: chaoplusplus   发布时间: 2011-12-12

#include <stdio.h>
#include <stdlib.h>
char s[]="00000000000000000000000000000001"
"00000000000000000000000000000010"
"00000000000000000000000000000011";
char *p;
char *ep;
char c;
unsigned long v;
FILE *f;
void main() {
  f=fopen("data.bin","wb");
  p=s;
  while (1) {
  if (0==*p) break;
  ep=p+32;
  c=*ep;
  *ep=0;
  v=strtoul(p,&ep,2);
  fwrite(&v,sizeof(v),1,f);
  *ep=c;
  p+=32;
  }
  fclose(f);
}

作者: zhao4zhong1   发布时间: 2011-12-12

谢谢赵老师
早知道有stroul这个函数我还用bitset 和string转来转去。
不过stroul函数转化出来的二进制数,大小有限制。bitset却可以很长
引用 1 楼 zhao4zhong1 的回复:

#include <stdio.h>
#include <stdlib.h>
char s[]="00000000000000000000000000000001"
"00000000000000000000000000000010"
"00000000000000000000000000000011";
char *p;
char *ep;
char c;
unsigned l……

作者: chaoplusplus   发布时间: 2011-12-12

说错了,是strtoul

作者: chaoplusplus   发布时间: 2011-12-12

分段用strtoul

作者: Lactoferrin   发布时间: 2011-12-12

可是怎样转回去呢?
由二进制得到01序列,有函数没?

作者: chaoplusplus   发布时间: 2011-12-12

itoa

作者: Lactoferrin   发布时间: 2011-12-12

OK!谢谢
引用 6 楼 lactoferrin 的回复:

itoa

作者: chaoplusplus   发布时间: 2011-12-12