【C语言】任意整数转二进制字符串

 上网看到一个将任意整数转二进制字符串的代码,修改了一下,共享出来:

IDE为:DevCPP

 
 
  1. #include <cstdlib> 
  2. #include <iostream> 
  3.  
  4. using namespace std; 
  5.  
  6.  
  7.  
  8. #define N 8 
  9. #define M 1<<(N-1) 
  10.  
  11. #define ERR     (0) 
  12. #define OK      (1) 
  13.  
  14.  
  15.  
  16. #define LOG_ERR(s)\ 
  17. {\ 
  18.     printf("line[%d], %s\n", __LINE__, s);\ 
  19.     system("pause");\ 
  20.  
  21. typedef unsigned int UL; 
  22. typedef unsigned short US; 
  23. typedef unsigned char UC; 
  24.  
  25.  
  26.  
  27. char inputFileName[] = "test.jpg"; 
  28. char outputFileName[] = "output.txt"; 
  29.  
  30. char binaryBuff[N + 1]; 
  31.  
  32.  
  33. void toBinaryString(UL num)     
  34. {        
  35.     int i;     
  36.  
  37.     memset(binaryBuff, 0, N + 1); 
  38.      
  39.     for (i=0; i<N ;i++)     
  40.     { 
  41.         if ((num&M)==0) 
  42.         { 
  43.             strcat(binaryBuff, "0"); 
  44.         } 
  45.         else 
  46.         { 
  47.             strcat(binaryBuff, "1"); 
  48.         } 
  49.          
  50.         num<<=1;     
  51.     }        
  52.  
  53.  
  54.  
  55.  
  56. int main() 
  57.     FILE *inputFile = NULL
  58.     FILE *outputFile = NULL
  59.  
  60.     char c = 0
  61.  
  62.  
  63.     inputFile = fopen(inputFileName, "rb"); 
  64.     if (NULL == inputFile) 
  65.     { 
  66.         LOG_ERR("call fopen(inputFileName, \"rb\") failed!"); 
  67.         return 0; 
  68.     } 
  69.  
  70.     outputFile = fopen(outputFileName, "wb"); 
  71.     if (NULL == inputFile) 
  72.     { 
  73.         LOG_ERR("call fopen(outputFileName, \"wb\") failed!"); 
  74.         return 0; 
  75.     } 
  76.  
  77.     while(c = fgetc(inputFile)) 
  78.     { 
  79.         if (feof(inputFile)) 
  80.         { 
  81.             break; 
  82.         } 
  83.  
  84.         toBinaryString(c); 
  85.  
  86.         fprintf(outputFile, "%s\n", binaryBuff); 
  87.     } 
  88.      
  89.     fflush(outputFile); 
  90.  
  91.     fclose(inputFile); 
  92.     fclose(outputFile); 
  93.      
  94.     system("pause"); 
  95.     return 0; 

 











本文转自fatshi51CTO博客,原文链接:http://blog.51cto.com/duallay/1139410 ,如需转载请自行联系原作者



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值