C语言输出二进制文件的问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C语言输出二进制文件的问题相关的知识,希望对你有一定的参考价值。

从键盘输入一段字符,要求:1.在屏幕上逐个打印出所输入字符的ASCII码2.把这些字符的ASCII码输出到二进制文件自己做调试半天,输出的二进制文件里都不是ASCII码,都是字符。麻烦各位网友帮忙,告诉我该怎么写。

  1、打开编译器,Ctrl+N新建一个文件;

  2、输入如下程序

  #include <stdio.h>

  #include <stdlib.h>

  int main()

  

  int a;

  char b[100];

  scanf("%d",&a);

  itoa(a,b,2);

  printf("%s",b);

  

  3、按F9编译

  4、按F5运行程序输入想要转化的数字即可,完成。

参考技术A #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
FILE* fp=fopen("a.txt","w+");
if(fp==NULL)
printf("open file error!");
return 0;

char buf[1024];
while(true)
printf("input the words,'exit' for exit:\n");
gets(buf);
if(strcmp(buf,"exit")==0)break;
else
for(int i=0;i<strlen(buf);i++)
printf("%c\t:\t%d\n",buf[i],buf[i]);
fprintf(fp,"%c:%d\r\n",buf[i],buf[i]);



fclose(fp);
printf("thks for use.");
system("a.txt");
system("pause");
return 0;
本回答被提问者采纳
参考技术B 只要用%x 和fprintf就行了啊 参考技术C 常去CSDN上看看 搜索一下 对以后有用 很多的

c语言的二进制数值如何直接输出?

1、首先打开vc6.0, 新建一个项目。

2、添加头文件。

3、添加main主函数。

4、定义一个两个数相加的函数binSubtracton。

5、在main函数定义int了性number1,number2, binSub。

6、使用scanf给变量赋值。

7、调用binAddition、binSubtracton。

8、使用printf打印结果。

参考技术A

C标准没有输出二进制的,不过用itoa()可以实现到二进的转换。

1、在C语言程序中,可以使用标准库函数中printf()来向屏幕输出信息,或者使用sprintf()向缓冲区输出信息。对整数而言,可以使用%d、%o、%x(或%X)输出十进制形式、八进制、十六进制形式,但貌似缺乏二进制形式。

2、解决方式有两种,一种是利用Windows提供的itoa()函数,另一种自行设计一个新的函数:

代码一:

/** Test.h */
#pragma once


#ifndef Test_H
#define Test_H


/** use itoa() to print integers in the form of binary 
 *  @param[in] n the integer to print
 *  @return void
 */
void printBinaryByItoa(unsigned int n);

代码二:

/** Test.c */
#include <stdio.h>
#include <stdlib.h>


void printBinaryByItoa(unsigned int n)

  unsigned char data[33];


  _itoa_s(n, data, 33, 2);
  
  printf("%sb\\n", data);



void printBinary(unsigned int n, unsigned char separator, unsigned char needPrefixZeros)

  unsigned int i = 0;
  unsigned int mask = 0;    /* the mask code to get each bit of n */
  unsigned char data[40];   /* the buffer to store the bits of n in the form of characters */
  unsigned int index = 0;   /* used to access data[] */
  unsigned int start = 0;   /* to point out where and when to store bits of n */
  
  data[39] = '\\0';

参考技术B 就像楼上说的,二进制是不可以直接输出的,但是可以用程序输出
#include<stdio.h>

void f(int n)

if(n) f(n/2);
else return;
printf("%d",n%2);


int main()

int n;
while(1)

scanf("%d",&n);
if(n<0) break;
if(n==0) printf("0");
f(n);
printf("\n");

return 0;
参考技术C void B_print (unsigned char B)//八位二进制输出

char j;
for(j=8;j>0;j--)printf("%d\t",(1&(B>>j)));


想要几位改循环次数和就行了

以上是关于C语言输出二进制文件的问题的主要内容,如果未能解决你的问题,请参考以下文章

网易云课堂_C语言程序设计进阶_第七周:文件:文件访问格式化输入输出二进制输入输出

c语言的二进制数值如何直接输出?

C语言-对文件的输入输出

c语言二进制文件操作

为啥C语言输出文件内容乱码

c语言文件操作