Thread: Bits operators

  1. #1
    Registered User
    Join Date
    Jun 2002
    Posts
    75

    Bits operators

    How do the bit operators work??
    How can I transform decimals into binarys or hexadecimals and viceversa????

    What are bit operators good for??
    ---Programming is like roaming, you never know where you'll end at------

    If 'here' is pronounced as 'hear', why 'there' isnt pronounced as 'dear'??

    [email protected]

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >How can I transform decimals into binarys or hexadecimals and viceversa????
    Converting a decimal value to hexadecimal is very simple. Just use printf with the %x flag. Decimal to binary is a bit more complex, but not a great deal. The following code illustrates one way to do it:
    Code:
    #include <stdio.h>
    
    static void printBin ( unsigned val )
    {
      if ( val != 0 )
        printBin ( val >> 1 );
      (void)putchar ( ( val & 1 ) != 0 ? '1' : '0' );
    }
    
    int main ( void )
    {
      printBin ( 27U );
      return 0;
    }
    printBin is a simple recursive function that checks if the value passed to it is 0. If it isn't then it will call itself again with the same value bit shifted right one space, this is done with the >> operator. When all of the original value has been shifted away the remaining value will be 0 and the function prints the value of the bit. All of the work is done in the print, where the first bit in the number is checked with &, and the appropriate character is printed.

    >How do the bit operators work??
    This has been answered before, try searching the boards so that I don't have to type it all again.

    >What are bit operators good for??
    See previous answer.

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Bitwise Operators
    By rrc55 in forum C Programming
    Replies: 6
    Last Post: 04-30-2009, 11:37 AM
  2. Bolean Operators hurt my head. (Trouble understanding) :(
    By Funcoot in forum C++ Programming
    Replies: 3
    Last Post: 01-20-2008, 07:42 PM
  3. SDLKey to ASCII without unicode support?
    By zacs7 in forum Game Programming
    Replies: 6
    Last Post: 10-07-2007, 03:03 AM
  4. Writing binary data to a file (bits).
    By OOPboredom in forum C Programming
    Replies: 2
    Last Post: 04-05-2004, 03:53 PM
  5. bitwise negation problem
    By Mr_Jack in forum C++ Programming
    Replies: 4
    Last Post: 03-15-2004, 08:16 PM