19.05.02--存储二进制数据

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Student
{
 char *name;  //名字
 int id;
 int name_len; //名字长度
}Stu;
int main()
{
 int x=0,n=0,i=0;
 int arr[64],name_arr[8];
 FILE *stream=fopen("1.txt","w");
 Stu s; //定义结构体变量
 //结构体成员赋值
 s.id = 1;
 s.name_len = strlen("mike"); //名字长度
 s.name = (char *)malloc(s.name_len + 1);
 strcpy(s.name, "mike");
 x = s.id ;
 while(x > 1)
 {
  n = x % 2 ;
  x /= 2 ;
  arr[31 - i++] = n ;
 }
 arr[31 - i++] = x % 2 ;
 x = s.name_len ;
 i = 0 ;
 while(x > 1)
 {
  n = x % 2 ;
  x /= 2 ;
  arr[63 - i++] = n ;
 }
 arr[63 - i++] = x % 2 ;
 for(int j = 0 ; j < 64 ; j++)
 {
  if(arr[j] != 1)
   fputs("0" , stream);
  else
   fputs("1" , stream);
  if(j % 4 == 3)fputs(" " , stream);
  if(j % 16 == 15)fputs("\n" , stream);
 }
 for(j = 0 ; j < s.name_len ; j++)
 {
  x = *(s.name + j);
  i = 0 ;
  while(x > 1)
  {
   n = x % 2 ;
   x /= 2 ;
   name_arr[7 - i++] = n ;
  }
  name_arr[7 - i++] = x % 2 ;
  for(i = 0 ; i < 8 ; i++)
  {
   if(name_arr[i] != 1)
    fputs("0" , stream);
   else
    fputs("1" , stream);
   if(i % 4 == 3)fputs(" " , stream);
  }
  if(j % 2 == 1)fputs("\n" , stream);
 }
 fclose(stream);
 return 0;
}

猜你喜欢

转载自www.cnblogs.com/redyellowblue/p/10802097.html
今日推荐