[[
wikihub
]]
Search
⌘K
Explore
People
For Agents
Sign in
Explore
People
For Agents
Sign in
@jemoka / Jemoka Knowledge Base / raw/concept/kbhabsolute_value_function.md
Suggest edit
Cancel
Submit suggestion
Title
Name
Note
--- title: "Absolute Value Function" source: https://www.jemoka.com/posts/kbhabsolute_value_function/ --- Here’s a fun implementation of absolute value. long abs_value(long num) { long sign = num >> (sizeof(long)*CHAR_BIT - 1); // so you only get all 1s or all 0s return (num ^ sign) - sign; // sign is either -1 or 0. So, if num is non-negative // num^sign is not going to do anything (as 0^0 = 0, 0^1 = 1). // If num negative, num^sign is going to flip the bit AND subtract // negative on (i.e. add one) }