/mordor/util.cpp
C++ | 59 lines | 26 code | 5 blank | 28 comment | 1 complexity | bb1c3c8ebb7ee9339a9aae9d45445bae MD5 | raw file
1#include "util.h" 2#include "endian.h" 3 4namespace Mordor 5{ 6 7// muldiv64() was adapted from 8// http://www.virtualbox.org/browser/trunk/src/VBox/Devices/muldiv64.c?rev=1 9// 10// the following copyright notice applies: 11/* 12 * QEMU System Emulator 13 * 14 * Copyright (c) 2003-2004 Fabrice Bellard 15 * 16 * Permission is hereby granted, free of charge, to any person obtaining a copy 17 * of this software and associated documentation files (the "Software"), to deal 18 * in the Software without restriction, including without limitation the rights 19 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 20 * copies of the Software, and to permit persons to whom the Software is 21 * furnished to do so, subject to the following conditions: 22 * 23 * The above copyright notice and this permission notice shall be included in 24 * all copies or substantial portions of the Software. 25 * 26 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 27 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 28 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 29 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 30 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 31 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 32 * THE SOFTWARE. 33 */ 34 35/* compute with 96 bit intermediate result: (a*b)/c */ 36uint64_t muldiv64(uint64_t a, uint32_t b, uint64_t c) 37{ 38 union { 39 uint64_t ll; 40 struct { 41#if MORDOR_BYTE_ORDER == MORDOR_BIG_ENDIAN 42 uint32_t high, low; 43#else 44 uint32_t low, high; 45#endif 46 } l; 47 } u, res; 48 uint64_t rl, rh; 49 50 u.ll = a; 51 rl = (uint64_t)u.l.low * (uint64_t)b; 52 rh = (uint64_t)u.l.high * (uint64_t)b; 53 rh += (rl >> 32); 54 res.l.high = (uint32_t)(rh / c); 55 res.l.low = (uint32_t)((((rh % c) << 32) + (rl & 0xffffffff)) / c); 56 return res.ll; 57} 58 59};