Android AP
Android AP

Reputation: 7

problem involving bits operation in C language

return (b & 0x20) ? b | ~0x3F : b & 0x3F;

is there is anyways to write this function with if and else or any other statement. I have tried this one down but it didn't work.

if (return (b & 32)) {
    b | ~63;
} else {
    b & 63;
}
}

Upvotes: 0

Views: 64

Answers (2)

yano
yano

Reputation: 5295

if (b & 0x20)
{
  return b | ~0x3F;
}
// else implied
return b & 0x3F;

Some coding standards don't like multiple return statements. Another option is

if (b & 0x20)
{
  b |= ~0x3F;
}
else
{
  b &= 0x3F;
}
return b;

However, this is different logic since the value of b is actually changing. If it's a local, no problems. Otherwise, there might be further reaching ramifications.

Upvotes: 1

David Grayson
David Grayson

Reputation: 87516

You just put your return in the wrong place. Try this:

if (b & 0x20) {
  return b | ~0x3F;
}
else {
  return b & 0x3F;
}

I don't think C lets you return from the middle of of an if condition, and even if it did, that would not match the behavior of your original line of code because you would be returning the wrong thing.

Upvotes: 1

Related Questions