Search code examples
cbit-manipulationlow-levellow-level-code

C code - a way to convert 5 to 7 and 7 to 5 without "if"


I want to write a function that gets a number X and if X=5 it returns 7 , if X=7 it return 5 otherwise, return something else. There is the trivial way - to use "if" blocks Another way - to use a map (5 mapped to 7, 7 mapped to 5) Third way - to write the matching linear mathematical equation BUT I'm looking for the 4th way of doing it (again - without using "if" blocks at all).

It feels like I need to use bit operation but I'm not dominant in this area so I need help.

Any ideas?

Thanks!


Solution

  • int fun(int p)
    {
        return p^2;
    }