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
A very timely thread:
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.
if your byte contains following bits:
R - reserved
S - suit
V - value
C - color
you'll do something like
to retrieve suit - first shift right to get rid of the bits from the left and create byte like
unsigned char card = 0x??;
int suit = (card >> 5) & 0x03 ;
and than - mask result to get rid of bits to the right
To set the suit do the opposite
First shift suit to the left to the correct bit position
unsigned char suit = 3;
card |= (suit << 5);
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:
Take the mask for the fied you need to clear
unsigned char card = ...;
card &= ~(0x3 << 5);
shift it to correct bit position
And use the Bit-wise AND to clear the corresponding bits
> A very timely thread:
Yes, except this one is a hell of a lot easier to map the suit into the colour ;)
To me bitpacking makes for a clearer picture but YMMV:
Packing Bits with Bit Fields