1. ## C Bit Manipulation

Hello fellow programmers,

I am new to the cprogramming forum and am requesting some assistance in further understanding bit manipulation in c.

I am undertaking my first attempt at learning c, as i have previously learnt c++.

I was confronted with a question regarding bit manipulation and using certain bits within a bit field to store values.

The question i was asked is that a card is made up of 7 bits.

2 bits = suit (Diamond, Clubs, Hearts, Spades)
4 bits = value (A,K,Q,J,10-2)
1 bit = colour (Black, Red)

Can someone please assist me in clearing up my understanding of bit operations ( bitwise &, bitwise OR,<< ,>>) and also provide an example of how the operations are carried out.

Thankyou fellow programmers

Sicilian_10

http://cboard.cprogramming.com/c-pro...ggestions.html

Here's what I'd like to see - post up something that has you stuck, or gives you the wrong answer, and let's deal with actual code.

A bit manipulation tutorial lies outside the bounds of a post on a forum, since there are already many such tutorials on the web (Google is your friend), and of course, in nearly every book as well.

Our time is limited, please be as specific as possible with your problem.

3. if your byte contains following bits:
R - reserved
S - suit
V - value
C - color

you'll do something like

Code:
```unsigned char card = 0x??;
int suit = (card >> 5) & 0x03 ;```
to retrieve suit - first shift right to get rid of the bits from the left and create byte like

and than - mask result to get rid of bits to the right

000000SS

To set the suit do the opposite
Code:
```unsigned char suit = 3;

card |= (suit << 5);```
First shift suit to the left to the correct bit position

0SS00000

Then use bit-wise OR to set the correct bits... (I suppose that you start with zero-bit sequence)

To clear corresponding bits use something similar:

Code:
```unsigned char card = ...;

card &= ~(0x3 << 5);```
Take the mask for the fied you need to clear
00000011

shift it to correct bit position

01100000

Invert it

10011111

And use the Bit-wise AND to clear the corresponding bits

4. > A very timely thread:
Yes, except this one is a hell of a lot easier to map the suit into the colour

5. To me bitpacking makes for a clearer picture but YMMV:
Packing Bits with Bit Fields