bit-packing

C++ Data Member Alignment and Array Packing

烈酒焚心 提交于 2019-11-27 06:44:33
问题 During a code review I've come across some code that defines a simple structure as follows: class foo { unsigned char a; unsigned char b; unsigned char c; } Elsewhere, an array of these objects is defined: foo listOfFoos[SOME_NUM]; Later, the structures are raw-copied into a buffer: memcpy(pBuff,listOfFoos,3*SOME_NUM); This code relies on the assumptions that: a.) The size of foo is 3, and no padding is applied, and b.) An array of these objects is packed with no padding between them. I've

How to create a byte out of 8 bool values (and vice versa)?

北战南征 提交于 2019-11-26 17:48:16
I have 8 bool variables, and I want to "merge" them into a byte. Is there an easy/preferred method to do this? How about the other way around, decoding a byte into 8 separate boolean values? I come in assuming it's not an unreasonable question, but since I couldn't find relevant documentation via Google, it's probably another one of those "nonono all your intuition is wrong" cases. The hard way: unsigned char ToByte(bool b[8]) { unsigned char c = 0; for (int i=0; i < 8; ++i) if (b[i]) c |= 1 << i; return c; } And: void FromByte(unsigned char c, bool b[8]) { for (int i=0; i < 8; ++i) b[i] = (c

How to create a byte out of 8 bool values (and vice versa)?

这一生的挚爱 提交于 2019-11-26 04:26:35
问题 I have 8 bool variables, and I want to \"merge\" them into a byte. Is there an easy/preferred method to do this? How about the other way around, decoding a byte into 8 separate boolean values? I come in assuming it\'s not an unreasonable question, but since I couldn\'t find relevant documentation via Google, it\'s probably another one of those \"nonono all your intuition is wrong\" cases. 回答1: The hard way: unsigned char ToByte(bool b[8]) { unsigned char c = 0; for (int i=0; i < 8; ++i) if (b