Skip to content
Home » Bitwise integer absolute value in C

Bitwise integer absolute value in C

Let’s start the discussion about Bitwise integer absolute value in C in following Approaches.

If a number is positive, we don’t need to do anything. We simply want to modify negative values. Because negative integers are kept in 2’s complement form, we must toggle bits of the number and add 1 to the result to retrieve the absolute value.

C bitwise integer absolute value

// Absolute value for integers
int a = -4268;
// mask = a >> 31 -> (mask ^ a) - mask
int abs = ((a >> 31) ^ a) - (a >> 31);

I hope the strategies listed above work for you. Happy coding and come back again.

Similar Post : Sleep in c programming