简体   繁体   中英

Is there a way to initialize a char using bits?

I'm trying to represent the 52 cards in a deck of playing cards. I need a total of 6 bits; 2 for the suit and 4 for the rank. I thought I would use a char and have the first 2 bits be zero since I don't need them. The problem is I don't know if there's a way to initialize a char using bits.

For example, I'd like to do is:

char aceOfSpades = 00000000;

char queenOfHearts = 00011101;

I know once I've initialized char I can manipulate the bits but it would be easier if I could initialize it from the beginning as shown in my example. Thanks in advance!

Yes you can:

example,

  char aceOfSpades = 0b00000000;
  char queenOfHearts = 0b00011101;

The easier way, as Captain Oblivious said in comments, is to use a bit field

struct SixBits
{
     unsigned int suit : 2;
     unsigned int rank : 4;
};

int main()
{
     struct SixBits card;
     card.suit = 0;        /*  You need to specify what the values mean */
     card.rank = 10;
}

You could try using various bit fiddling operations on a char , but that is more difficult to work with. There is also a potential problem that it is implementation-defined whether char is signed or unsigned - and, if it is signed , bitfiddling operations give undefined behaviour in some circumstances (eg if operating on a negative value).

Personally, I wouldn't bother with trying to pack everything into a char . I'd make the code comprehensible (eg use an enum to represent the sut, an int to represent rank) unless there is demonstrable need (eg trying to get the program to work on a machine with extremely limited memory - which is unlikely in practice with hardware less than 20 years old). Otherwise, all you are really achieving is code that is hard to maintain with few real-world advantages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM