From bd2b53ccc493b4a9b82ba936ca23f17ca9cbde2f Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Mon, 20 Jan 2014 02:31:12 +0100 Subject: m + add abs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Mattias Andrée --- src/algorithms/bits/Absolute.java | 44 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/algorithms/bits/Absolute.java (limited to 'src/algorithms/bits/Absolute.java') diff --git a/src/algorithms/bits/Absolute.java b/src/algorithms/bits/Absolute.java new file mode 100644 index 0000000..2e694eb --- /dev/null +++ b/src/algorithms/bits/Absolute.java @@ -0,0 +1,44 @@ +/** + * Copyright © 2014 Mattias Andrée (maandree@member.fsf.org) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package algorithms.bits; + + +/** + * Compute the absolute value of an integer + */ +public class Absolute +{ +£S=${T_S#*_} + /** + * Compute the absolute value of an integer + * + * @param value The integers + * @return The absolute value, the most negative value will because of overflow return the value itself + */ + public static £{T} abs(£{T} value) + { + £{T} mask;; + return (value ^ (mask = value >> £{S})) - mask; + /* Or alternatively: + * (v + (mask = value >> £{S})) ^ mask + */ + } +£>done +} + -- cgit v1.2.3-70-g09d2