Mask

This is a discussion on Mask within the C++ Programming forums, part of the General Programming Boards category; In essence, how would you use a unsigned short as a bit mask ? --What's the best way to print ...

  1. #1
    Unregistered
    Guest

    Mask

    In essence, how would you use a unsigned short as a bit mask ?

    --What's the best way to print the bits and use/manipulate them ?


    Thanks
    ---------

  2. #2
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,386
    >In essence, how would you use a unsigned short as a bit >mask ?

    A mask can be used to check if a certain bit, or bits, is set or not.

    To check if bit 2 is set (note that bit 0 is the first bit), you need the following mask:

    unsigned short mask = 0x04;

    To check if bit 2 is set, you could do:

    if (variable & mask)
    {
    /* the bit is set */
    }

    >What's the best way to print the bits and use/manipulate them?

    Manipulation with bits can be done best with the bit-operators, look them up in your C book.

    To print a byte in binary, you could do something like:

    Code:
        unsigned char value = 0x11; /* just a value */
        unsigned char mask = 0x80;
        unsigned char bits [8];
        int i;
    
        for (i = 0; i < 8; i++)
        {
            bits [i] = ((value & mask) != 0);
            mask >>= 1; /* shift all bits one to right */
            printf ("%d", bits [i]);
        }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. inotify woes
    By quixote in forum Linux Programming
    Replies: 6
    Last Post: 01-26-2008, 12:58 AM
  2. bit shifting a mask
    By detfella in forum C++ Programming
    Replies: 1
    Last Post: 02-25-2004, 04:13 PM
  3. C diamonds and perls :)
    By Carlos in forum A Brief History of Cprogramming.com
    Replies: 7
    Last Post: 05-16-2003, 10:19 PM
  4. Help About The ENIGMA Algoritm
    By JohnnyAtomic in forum C Programming
    Replies: 4
    Last Post: 02-22-2002, 09:05 AM
  5. Replies: 3
    Last Post: 12-15-2001, 12:46 PM

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