如何乘以c中的32位整数 [英] How to multiply 32-bit integers in c
本文介绍了如何乘以c中的32位整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
执行:
#define HIGH32(V64)((uint32_t)((V64>> 32)& amp ; 0xffFFFFFF))
#define LOW32(V64)((uint32_t)(V64& 0xffFFffFF))
uint32_t a = 0xffFFffFF;
uint32_t b = 0xffFFffFF;
uint64_t res = a * b;
printf(res =%08X%08X \\\
,HIGH32(res),LOW32(res));
给出:
res = 00000000 00000001
但我预计:fffffffe00000001。我做错了什么?单一作业:
res = 0x0123456789ABCDEF;
printf(res =%08X%08X \\\
,HIGH32(res),LOW32(res));
给出
res = 01234567 89ABCDEF
环境:
$ gcc --version
gcc(GCC)4.8.3
版权所有(C)2013自由软件基金会,Inc.
$ gcc -v
COLLECT_GCC = gcc
COLLECT_LTO_WRAPPER = / usr / lib / gcc / i686-pc-cygwin / 4.8.3 / lto-wrapper.exe
dest arch:i686- pc-cygwin
$文件a.exe
a.exe:PE32可执行文件(控制台)Intel 80386,用于MS Windows
解决方案
您目前有:
uint64_t res =(uint32_t)a *(uint32_t)b;
您需要在乘法之前将参数提升为64位数字。因此:
uint64_t res =(uint64_t)a * b;
Execution of:
#define HIGH32(V64) ((uint32_t)((V64 >> 32)&0xffFFffFF))
#define LOW32(V64) ((uint32_t)(V64&0xffFFffFF))
uint32_t a = 0xffFFffFF;
uint32_t b = 0xffFFffFF;
uint64_t res = a * b;
printf("res = %08X %08X\n", HIGH32(res), LOW32(res));
Gives:
"res = 00000000 00000001"
But I expect: fffffffe00000001. What did I do wrong? Single assignment:
res = 0x0123456789ABCDEF;
printf("res = %08X %08X\n", HIGH32(res), LOW32(res));
Gives
res = 01234567 89ABCDEF
Environment:
$gcc --version
gcc (GCC) 4.8.3
Copyright (C) 2013 Free Software Foundation, Inc.
$ gcc -v
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/i686-pc-cygwin/4.8.3/lto-wrapper.exe
dest arch: i686-pc-cygwin
$ file a.exe
a.exe: PE32 executable (console) Intel 80386, for MS Windows
解决方案
You currently have:
uint64_t res = (uint32_t) a * (uint32_t) b;
You will want to promote the arguments to 64bit numbers before the multiplication. Therefore:
uint64_t res = (uint64_t) a * b;
这篇关于如何乘以c中的32位整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文