Created
April 26, 2012 11:36
-
-
Save zhpengg/2498982 to your computer and use it in GitHub Desktop.
32为整数保存32位乘法结果
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <cstdlib> | |
#include <stdint.h> | |
struct UInt64 { | |
uint32_t high; | |
uint32_t low; | |
}; | |
UInt64 multiply(uint32_t a, uint32_t b) | |
{ | |
uint16_t ah = (a >> 16) & 0xFFFF; | |
uint16_t al = a & 0x0FFFF; | |
uint16_t bh = (b >> 16) & 0xFFFF; | |
uint16_t bl = b & 0x0FFFF; | |
uint32_t h = ah * bh; | |
uint32_t l = al * bl; | |
uint32_t m0 = ah * bl; | |
uint32_t m1 = al * bh; | |
uint32_t m = m1 + m0; | |
// 加法溢出 | |
if (m < m0 || m < m1) { | |
h += (1 << 16); | |
} | |
struct UInt64 result; | |
result.high = h + ((m >> 16) & 0x0FFFF); | |
result.low = l + ((m & 0x0FFFF) << 16); | |
// 加法溢出 | |
if (result.low < l || result.low < ((m & 0x0FFFF) << 16)) { | |
result.high += 1; | |
} | |
return result; | |
} | |
int main() | |
{ | |
uint32_t a = 0xabcdef11; | |
uint32_t b = 0xabcdef22; | |
struct UInt64 pro = multiply(a, b); | |
printf("%X %X\n", pro.high, pro.low); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment