Trevor
Trevor

Reputation: 6689

Getting value of last 2 bits in an unsigned char

I have an unsigned char and I need to check bits 1 and 2 to find the status. What is the best way to determine the last 2 bits?

I am attempting to perform an OR, but my results aren't correct. Any help would be appreciated. Thanks.

Example:

10101000 = off
10101001 = on
10101010 = error
10101011 = n/a

if(data_byte_data[0] | 0xfe)
    //01
else if(data_byte_data[0] | 0xfd)
    //10;
else if(data_byte_data[0] | 0xfc)
    //11
else if(data_byte_data[0] | 0xff)
    //00

Upvotes: 1

Views: 1921

Answers (4)

Jerry Coffin
Jerry Coffin

Reputation: 490048

switch(data_byte_dat[0] & 3) {
    case 0: puts("off");    break;
    case 1: puts("on");     break;
    case 2: puts(""error"); break;
    case 3: puts("N/A");
}

Upvotes: 3

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84151

switch ( val & 3 ) {
    case 0: // 00
    case 1: // 01
    case 2: // 10
    case 3: // 11
}

Upvotes: 0

John Bode
John Bode

Reputation: 123458

switch(data_byte_data[0] & 0x0003)
{
  case 0: 
    // 00
    break;

  case 1:
    // 01
    break;

  case 2:
     // 10
     break;

  case 3:
     // 11
     break;
}

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

I would do something like:

v = data_byte_data[0] & 0x03;
switch (v)
{
case 0: ...
case 1: ...
case 2: ...
case 3: ...
}

Upvotes: 8

Related Questions