Home > Mobile >  problem involving bits operation in C language
problem involving bits operation in C language

Time:12-01

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;
}
}

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related