home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #26 / NN_1992_26.iso / spool / comp / lang / c / 16494 < prev    next >
Encoding:
Text File  |  1992-11-14  |  1.1 KB  |  41 lines

  1. Path: sparky!uunet!ukma!darwin.sura.net!sgiblab!munnari.oz.au!jabaru.cec.edu.au!csource!gateway
  2. From: Scott.Pitcher@f395.n634.z3.fidonet.org (Scott Pitcher)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How to print an integer as binary?
  5. Message-ID: <721610886.AA08867@csource.oz.au>
  6. Date: Wed, 11 Nov 1992 06:40:00 +1100
  7. Sender: gateway@csource.oz.au
  8. Lines: 31
  9.  
  10.  TO> Assuming that:- 
  11.  TO> 
  12.  TO> int i = 203;
  13.  TO> 
  14.  TO> How do I display 'i' as 11001011?
  15.  
  16. #include <stdio.h>
  17. #include <values.h>
  18.  
  19. void main()
  20. {
  21.         int i, j;
  22.  
  23.         printf("\nEnter 'i' : ");
  24.         scanf("%d", &i);
  25.         for(j = 0; j < 16; i <<= 1, ++j)
  26.                 printf("%c", (i & MAXINT + 1) ? '1' : '0');
  27.         printf("\n%u", MAXINT + 1);
  28.  
  29. }
  30.  
  31. This will print with leading zeros and it assumes that the integer is
  32. 16 bits wide, but it is simple and it works. What more could you want?
  33.  
  34. Scott.
  35.  
  36. P.S. If you were using FORTH instead of C, a simple "2 BASE" would
  37. allow you to print in Binary with out any hassles, and no leading
  38. zeros.
  39.  
  40.  * Origin: Starbase Alpha On the Edge of the Universe! (3:634/395.0)
  41.