ains
ains

Reputation: 1446

How to get the least significant 3 bits of a char in C++?

The following text is what I'm stuck with on a piece of documentation.

The least significant 3 bits of the first char of the array indicates whether it is A or B. If the 3 bits are 0x2, then the array is in a A format. If the 3 bits are 0x3, then the array is in a B format.

This is the first time in my life I have ever touched on with this least significant bits thingy. After searching on StackOverflow, this is what I did:

int lsb = first & 3;
if (lsb == 0x02)
{
    // A
}
else if (lsb == 0x03)
{
    // B
}

Is this correct? I want to ensure this is the right way (and avoid blowing my foot off later) before I move on.

Upvotes: 0

Views: 2038

Answers (4)

datenwolf
datenwolf

Reputation: 162317

d3 = b11 = b01 | b10

So no, right now you're comparing only the 2 LSBs. b111 would be d7

If you want to write down the number of bits to take, You'd have to write it as

unsigned int ls3b = ~(UINT_MAX << 3);

what this does is, it takes the all 1 bit array, shifts it by 3 bits to the left (leaving the 3 LSBs 0) and then inverts it.

Upvotes: 0

QuentinC
QuentinC

Reputation: 14772

Normally, 3 least significant bits should be yourchar&0x07 unstead.

7 because 7 is 1+2+4 or binary 111, corresponding to the 3 LSB.

EDIT: grilled, should be deleted. Sorry.

Upvotes: 2

Etherealone
Etherealone

Reputation: 3558

The variable you need will have every bit zero and three LSBs 1, which is 0111 in short.

0111 is 0x7, use variable & 0x7 to mask your variable.

Google bit masking for more information about it.

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70999

The least significant 3 bits of x are taken using x&7 unlike the first & 3 you use. In fact first & 3 will take the least significant 2 bits of first.

You should convert the numbers to binary to understand why this is so: 3 in binary is 11, while 7 is 111.

Upvotes: 4

Related Questions