Reputation: 1
I need to pack a bool value into a byte. The byte can contain one of these characters.
(0 to 9 and A to F) i.e. hex characters.
I believe that these chars are essentially taking 7 bits so how can we utilize the 8th bit to store a bool value and retrieve both at a later stage?
Upvotes: 0
Views: 537
Reputation: 171167
You could do this:
char pack(char c, bool b) {
char res = c;
if (b) {
res |= 128;
}
return res;
}
void unpack(char packed, char &c, bool &b) {
b = ((packed & 128) > 0);
c = packed & 127;
}
To facilitate manipulating just one part of the packed value, you can also add functions like this:
char unpackChar(char packed) {
return packed & 127;
}
bool unpackBool(char packed) {
return ((packed & 128) > 0);
}
If you add them, redefine unpack()
with them, not to duplicate information:
void unpack(char packed, char &c, bool &b) {
c = unpackChar(packed);
b = unpackBool(packed);
}
Example use:
char packed = pack('A', true);
std::cout << unpackChar(packed);
Upvotes: 2
Reputation: 110728
The number of bits that your char
is utilizing entirely depends on how you're using it. If the execution character set of your compiler is ASCII compatible and you are storing characters within the ASCII range 0-127 in a char
(perhaps by using character literals), then you have an extra bit to spare (if CHAR_BIT == 8
).
If you're storing only the hexadecimal characters as ASCII characters, then you really you have an extra two bits, because you're using characters within the 0-63 range.
Nonetheless, if you want to store a boolean variable in the 8th bit of your char
, you can simply bit shift a bool
value and then bitwise OR it with your char
:
char c = 'A';
bool b = true;
c |= (b << 7);
Note, however, that you cannot print out this char
and expect to still see A
. The char
has a different value now.
Upvotes: 0