Bit Usage

This is a discussion on Bit Usage within the C Programming forums, part of the General Programming Boards category; I was working on a project, and how do i use individual bits, i thought of using bools, but they ...

  1. #1
    Wannabe Geek
    Join Date
    Aug 2004
    Posts
    19

    Bit Usage

    I was working on a project, and how do i use individual bits,
    i thought of using bools, but they take up a byte.
    Is there i can declare and manipulate individual bits.
    An int is stored in 4 bytes, but when i "&" two ints i get a 1 or a 0. Could u please explain how i could go about creating a program to display the bits of an int.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,333
    Code:
    unsigned int value = 0x1234;
    unsigned int mask = 1;
    if ( ( value & mask ) != 0 ) putchar('1') else putchar('0');  // display a bit
    mask = mask << 1;  // select the next bit
    Wrap those ideas up in a loop, and you're about done
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,246
    I think you need to change your mask for that to work Salem. You displaying the least significant bit, but shifting to the left each time (which will shift in 0s).

    Code:
    #include <stdio.h>
    
    int main()
    {
    	int someInt = 0x12345678;
    	int bytesInInt;
    	int i;
    
    	bytesInInt = sizeof(int) * 8;
    
    	for(i = 0; i < bytesInInt; i++)
    	{
    		if(someInt & 0x80000000)
    			printf("1");
    		else
    			printf("0");
    		someInt = someInt << 1;
    	}
    	printf("\n");
    
        return 0;
    }

  4. #4
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,246
    oops, I should have named that variable "bitsInInt" instead

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by bithub
    I think you need to change your mask for that to work Salem. You displaying the least significant bit, but shifting to the left each time (which will shift in 0s).
    Well, you'd be wrong in thinking that.

    1 << 0 = 1
    1 << 1 = 2
    1 << 2 = 4
    1 << 3 = 8
    ...and so on...

    Thus, the mask slides down one bit at a time until it reaches the end. Salem is rarely wrong. The only problem in the code is a simple typo:
    Code:
    if ( ( value & mask ) != 0 ) putchar('1'); else putchar('0');  // display a bit
    Forgot a semi-colon. Other than that, it works as intended. Try throwing it in a loop, as suggested, to see for yourself. On an aside:
    Code:
    bytesInInt = sizeof(int) * 8;
    This really should be:
    Code:
    bitsInInt = sizeof(int) * CHAR_BIT;
    Which is found in <limits.h>.

    Quzah.
    Hope is the first step on the road to disappointment.

  6. #6
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,333
    It was a clue, not an answer!
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  7. #7
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,246
    My mistake. His code shifts the mask, and mine shifts the integer. That is what got me on the wrong track

  8. #8
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Quote Originally Posted by quzah
    This really should be:
    Code:
    bitsInInt = sizeof(int) * CHAR_BIT;
    Nit.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  9. #9
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Nit.
    Yes, but who is willing to trade a nice compile-time constant for a run-time loop check? It's better to just avoid mixing size calculations with bitwise operations to begin with.
    My best code is written with the delete key.

  10. #10
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Quote Originally Posted by Prelude
    >Nit.
    Yes, but who is willing to trade a nice compile-time constant for a run-time loop check?
    Certainly not me, which is why my first post in that thread used a value-based expression that can resolve into a compile-time constant for the highest bit of an unsigned int.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  11. #11
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    Quote Originally Posted by Dave_Sinkula
    Certainly not me, which is why my first post in that thread used a value-based expression that can resolve into a compile-time constant for the highest bit of an unsigned int.
    I assume you mean this expression:
    Code:
    char binary[sizeof(value) * CHAR_BIT + 1];
    In which case it's still not portable, but there's nothing wrong with it either. The reason it isn't portable is because sizeof takes the size of an expression from the type of the expression's result. So the above sizeof expression is equivalent to
    Code:
    sizeof ( int ) * CHAR_BIT + 1
    Precisely what you were warning against in your little nitpick. The reason is isn't wrong is because you don't need the exact number of bits for a bitwise operation, you simply need enough memory to hold the upper bound number of bits in an integer, which the expression sizeof ( int ) * CHAR_BIT handles quite nicely.

    The only way I know of to get the number of value bits is a run-time loop that relies on the fact that the bitwise operators only work with value bits:
    Code:
    #include <limits.h>
    #include <stdio.h>
    
    unsigned int value_bits ( void )
    {
      unsigned int n = 1U;
      unsigned int value = UINT_MAX;
    
      while ( ( value >>= 1U ) != 0 )
        ++n;
    
      return n;
    }
    
    int main ( void )
    {
      printf ( "value_bits: %u\n", value_bits() );
    
      return 0;
    }
    My best code is written with the delete key.

  12. #12
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Quote Originally Posted by Prelude
    I assume you mean this expression:
    Code:
    char binary[sizeof(value) * CHAR_BIT + 1];
    No, I didn't mean that part. Sorry I wasn't clear.

    I meant the part about needing to find out the number of bits in an int. You don't need to do so to loop through all the value bits. You can just set the high bit and right shift until you are out of bits.

    Since I'm mincing words frequently lately, here's kinda what I mean.
    Code:
    #include <stdio.h>
    
    int main(void)
    {
       unsigned int mask, value = 125;
       for ( mask = (-1U >> 1) + 1; mask; mask >>= 1 )
       {
          putchar(value & mask ? '1' : '0');
       }
       putchar('\n');
       return 0;
    }
    
    /* my output
    00000000000000000000000001111101
    */
    As far as I know, this -- as well as other similar constructs -- doesn't assume that all bits of an int are value bits, but still sets the high bit in an expression that can resolve into a compile-time constant.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  13. #13
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >No, I didn't mean that part.
    Oh, my bad.

    >You don't need to do so to loop through all the value bits.
    I know, but to do so I don't know of any compile-time way to figure it out. That was my point since your nitpick was concerning such a calculation (ie. an expression resolving to, say, 32 - padding for a 32 bit integer type that could be assigned to a variable), and probably why your mention of a compile-time constant that does it in your post confused me.

    At least we agree that using bitwise shifting is a portable way to process all of the value bits.
    My best code is written with the delete key.

  14. #14
    Wannabe Geek
    Join Date
    Aug 2004
    Posts
    19
    Thanx for the help.
    But how do i manipulate individual bits, is there an prog that can be created to change the individual bits,could i target a particular bit in the 4 bytes for an integer and change it to 1 or 0.
    - Cheers.

  15. #15
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,333
    > But how do i manipulate individual bits,

    1 << n
    selects a bit

    value | mask
    sets bit(s)

    value & ~mask
    clears bit(s)

    value ^ mask
    toggles bit(s)
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 11-10-2005, 09:53 AM
  2. porting application from 32 bit to 64 bit error
    By gandalf_bar in forum Linux Programming
    Replies: 1
    Last Post: 09-14-2005, 09:20 AM
  3. Bit processing in C
    By eliomancini in forum C Programming
    Replies: 8
    Last Post: 06-07-2005, 10:54 AM
  4. Bit Manipulation Questions
    By CPPNewbie in forum C++ Programming
    Replies: 7
    Last Post: 08-12-2003, 02:17 PM
  5. Array of boolean
    By DMaxJ in forum C++ Programming
    Replies: 11
    Last Post: 10-25-2001, 11:45 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21