From Bit Twiddling Hacks:
int v; // we want to find the absolute value of v
unsigned int r; // the result goes here
int const mask = v >> sizeof(int) * CHAR_BIT - 1;
r = (v + mask) ^ mask;
More Related Contents:
- Determine if int is not 0 with no if statements
- Invalid solution for code challenge with operator restrictions
- How do you set, clear, and toggle a single bit?
- Best practices for circular shift (rotate) operations in C++
- Position of least significant bit that is set
- How to create a byte out of 8 bool values (and vice versa)?
- Examples of when a bitwise swap() is a bad idea?
- C/C++: Force Bit Field Order and Alignment
- What is the efficient way to count set bits at a position or lower?
- What is the idea behind ^= 32, that converts lowercase letters to upper and vice versa?
- C/C++ check if one bit is set in, i.e. int variable
- How do I set, clear, and toggle a single bit?
- In C/C++ what’s the simplest way to reverse the order of bits in a byte?
- Weird behavior of right shift operator (1 >> 32)
- Should I use #define, enum or const?
- How to add two numbers without using ++ or + or another arithmetic operator
- What happens when you bit shift beyond the end of a variable?
- What’s the fastest way to pack 32 0/1 values into the bits of a single 32-bit variable?
- Efficient bitwise operations for counting bits or find the right|left most ones
- Performance wise, how fast are Bitwise Operators vs. Normal Modulus?
- Branchless code that maps zero, negative, and positive to 0, 1, 2
- Fastest way to produce a mask with n ones starting at position i
- How to set, clear, and toggle a single bit?
- Fast divisibility tests (by 2,3,4,5,.., 16)?
- How can I test whether a number is a power of 2?
- Using G++ to compile multiple .cpp and .h files
- What is the (“spaceship”, three-way comparison) operator in C++?
- How do you implement Coroutines in C++
- References Needed for Implementing an Interpreter in C/C++
- How can a char pointer be initialized with a string (Array of characters) but an int pointer not with an array of integer? [duplicate]