C语言 需要在C中将2的补码转换为十进制的最快方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2689028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Need fastest way to convert 2's complement to decimal in C
提问by kp11
I have a certain 18 bits (which are in 2's complement) within 32 bits. I need to convert them to decimal. Please show me a code snippet in C.
我在 32 位内有一定的 18 位(在 2 的补码中)。我需要将它们转换为十进制。请给我看一段 C 语言的代码片段。
回答by unwind
First you need to do sign extensionon your 18 bits, to fill out the native int:
首先,您需要对18 位进行符号扩展,以填写本机int:
const int negative = (smallInt & (1 << 17)) != 0;
int nativeInt;
if (negative)
nativeInt = smallInt | ~((1 << 18) - 1);
else
nativeInt = smallInt;
If the number is considered negative (i.e. bit 17 is set), we bitwise-or it with a bit pattern that has ones in all the remaining bits. This creates the proper negative native-sized integer.
如果该数字被认为是负数(即第 17 位已设置),我们将按位或使用一个位模式,该位模式在所有剩余位中都为 1。这将创建适当的负本机大小的整数。
Then just print the native integer as usual, since you sound as if you need a decimal string representation:
然后像往常一样打印本机整数,因为您听起来好像需要十进制字符串表示:
char buf[12];
snprintf(buf, sizeof buf, "%d", nativeInt);
Of course, this last part might not at all match your expectaions; it's not perhaps "fastest". Since you have a limited input range of 18 bits, it's probably possible to come up with something a bit more optimized.
当然,最后一部分可能完全不符合您的期望;它也许不是“最快的”。由于您的输入范围有限,只有 18 位,因此可能会想出一些更优化的东西。
A few ideas:
一些想法:
- Remove the buffer size argument (i.e. use
sprintf()) since we can be quite sure about the maximum number of characters needed. - Since we know the range, use something less general that never checks for values outside the range.
- Use
itoa()if you have it, less general thans*printf()so might be faster.
- 删除缓冲区大小参数(即 use
sprintf()),因为我们可以非常确定所需的最大字符数。 - 因为我们知道范围,所以使用不那么通用的东西,从不检查范围之外的值。
itoa()如果你有它,请使用它,不那么通用s*printf()可能会更快。
回答by inigo333
I've tried this myself and works just fine:
我自己试过这个并且工作得很好:
int binTwosComplementToSignedDecimal(char binary[],int significantBits)
{
int power = pow(2,significantBits-1);
int sum = 0;
int i;
for (i=0; i<significantBits; ++i)
{
if ( i==0 && binary[i]!='0')
{
sum = power * -1;
}
else
{
sum += (binary[i]-'0')*power;//The -0 is needed
}
power /= 2;
}
return sum;
}
Sample:
样本:
char binary[8] = '10000001';
int significantBits = 8;
int decimal = binTwosComplementToSignedDecimal(binary,significantBits);
Results in
结果是
decimal = -127

