问题描述
我有一个整数数组,它们代表一个二进制数。我需要将其转换为等效的十进制整数。有人可以帮我吗?
static
在这种情况下,我想返回的十进制等效值为 74 。
解决方法
这是如何执行类似操作的示例:
#include <stdio.h>
int main()
{
int octet[] = {0,1,0};
int *p = octet;
int len = sizeof(octet) / sizeof(octet[0]); // 8
unsigned result = 0;
while(len--) result = (result<<1) | *p++;
/* 74 */
printf("%u\n",result);
}
,
2 ^ 0 x最后一个元素+ 2 ^ 1 x倒数第二个元素+ 2 ^ 2 x倒数第二个元素+ ...
,#include <stdio.h>
int main()
{
// Make array constant and let the compiler tell us how many elements are contained.
// Doing it this way allows "octet" to grow up to the number of bits in an integer elements.
// It won't be an "octet" anymore though,...
const int octet[] = {0,0};
const int NumArrayElements = sizeof(octet) / sizeof(*octet);
// Assign hi bit to save a loop iteration.
int value = octet[0];
// Run remaining bits,shifting up and or-ing in new values.
for(int i=1; i<NumArrayElements; i++)
{
value <<= 1;
value |= octet[i];
}
printf("%d\n",value);
}
这是一件简单的事情,但是让编译器处理一些大小调整问题并添加注释可以使维护工作变得更加容易。