Thread: Value to binary number.

  1. #1
    Learning C. JOZZY& Wakko's Avatar
    Join Date
    Nov 2009
    Posts
    59

    Value to binary number.

    When calculating the value of a binary number for example 10010111 I need to do the following.
    (1*2^7) + (0*2^6) + (0*2^5) + (1*2^4) + (0*2^3) + (1*2^2) + (1*2^1) + (1*2^0) = 128 + 0 + 0 + 16 + 0 + 4 + 2 + 1 = 151
    But what if I am given the number 456 and I need to convert this value into a binary number. How would I do this this?

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by JOZZY& Wakko View Post
    But what if I am given the number 456 and I need to convert this value into a binary number.
    It's already stored that way. Ironically, there is no standard method for presenting a binary number in human readable output in C -- the way that %d and %x work for decimal and hexadecimal.

    So you have to turn int x=456 into a string, "111001000". I'll give you a clue:
    Code:
    	int x=456, i;
    	for (i=512; i>0; i/=2) {
    the next step involves testing with AND (x&i).
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 10-07-2006, 05:37 AM
  2. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM
  3. large binary number division
    By nappaji in forum C Programming
    Replies: 3
    Last Post: 08-08-2006, 01:54 PM
  4. large binary number division
    By nappaji in forum C++ Programming
    Replies: 1
    Last Post: 08-08-2006, 12:01 AM
  5. Printing total of 1's in binary number
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 11-18-2001, 02:50 PM