labs.c (1553B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2020 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 #include "stdlib/math/base/special/labs.h" 20 #include <stdint.h> 21 22 /** 23 * Computes the absolute value of a signed 32-bit integer in two's complement format. 24 * 25 * ## Method 26 * 27 * - Assume two's complement format. 28 * - Create a mask by applying a sign propagating right-shift. For negative integers, this results in all `1`'s. For nonnegative integers, this results in all `0`'s. 29 * - XOR the mask with `x`. For negative integers, this is the equivalent of a NOT. For nonnegative integers, this is a no-op. 30 * - Subtract the mask to recover the absolute value. For negative integers, this adds `1`, which is `-x` when using two's complement. For nonnegative integers, this subtracts `0`. 31 * 32 * @param x number 33 * @return absolute value 34 * 35 * @example 36 * #include <stdint.h> 37 * 38 * int32_t y = stdlib_base_labs( -5 ); 39 * // returns 5 40 */ 41 int32_t stdlib_base_labs( const int32_t x ) { 42 int32_t mask = x >> 31; 43 return (x ^ mask) - mask; 44 }