#include
#include
//PRINTBIT 用于把一无符号整数翻译成二进制串
void PRINTBIT(unsigned int number)
{
unsigned int i;
unsigned int ckecker=1;//ckecker 用于指示由右至左的位数,初置设为 1
ckecker<<=8-1;//将 ckecker 中非零位移到其机器表示的最左边
//下一语句从左至右打印各位,每四位之间留一空隔
for (i=1;i<=8;i++)
{
//打印 ckecker 非零位所对应的 number 中对应位
putchar((number & ckecker)?'1':'0');
if (i%4==0)//每4位用空格隔开
putchar(' ');
ckecker>>=1; //准备打印 number 中的下一位
}
putchar('\n');
}
int main(void)
{
FILE *fp;
char *filename = "in1.dat";
char ch;
if((fp=fopen(filename,"rb"))== NULL )
{
printf("Can not open %s!\n",filename);
exit(0);
}
printf("原字符\t二进制\n");
ch=fgetc(fp);//取字符
while(!feof(fp))
{
putchar(ch);
putchar('\t');
PRINTBIT(ch);
ch=fgetc(fp);
}
fclose(fp);
return 0;
}
二进制打开文件fopen(filename,"rd")
二进制读可以用 fscanf()
#include
#include
#include
int main(void)
{
FILE * fp;
char * filename = "test.dat";
int i;
char str[128];
if( (fp=fopen(filename,"rb"))== NULL )
{
printf("Can not open %s!\n",filename);
exit(0);
}
while(!feof(fp))
{
fscanf(fp,"%d",&i);
itoa(i, str, 2);
printf("%s ",str);
}
fclose(fp);
return 0;
}