简体   繁体   English

有没有办法使用位初始化char?

[英]Is there a way to initialize a char using bits?

I'm trying to represent the 52 cards in a deck of playing cards. 我试图代表一副扑克牌中的52张牌。 I need a total of 6 bits; 我需要总共6位; 2 for the suit and 4 for the rank. 2为西装,4为排名。 I thought I would use a char and have the first 2 bits be zero since I don't need them. 我以为我会使用char并且前两位为零,因为我不需要它们。 The problem is I don't know if there's a way to initialize a char using bits. 问题是我不知道是否有办法使用位初始化char。

For example, I'd like to do is: 例如,我想做的是:

char aceOfSpades = 00000000; char aceOfSpades = 00000000;

char queenOfHearts = 00011101; 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. 我知道一旦我初始化了char,我可以操作这些位,但如果我可以从头开始初始化它会更容易,如我的例子所示。 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 正如Captain Oblivious在评论中所说的那样,更简单的方法就是使用一点点字段

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. 你可以尝试在char上使用各种bit fiddling操作,但这更难以使用。 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). 还有一个潜在的问题是,无论char是有signed还是unsigned ,它都是实现定义的 - 如果有signed ,bitfiddling操作在某些情况下会给出未定义的行为(例如,如果在负值下运行)。

Personally, I wouldn't bother with trying to pack everything into a char . 就个人而言,我不打算尝试将所有东西都装入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). 我将使代码易于理解(例如,使用枚举来表示sut, int来表示排名),除非有明显的需求(例如,试图让程序在内存极其有限的机器上工作 - 这在实践中不太可能硬件不到20年)。 Otherwise, all you are really achieving is code that is hard to maintain with few real-world advantages. 否则,你真正实现的只是代码难以维护,几乎没有现实世界的优势。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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