应用中的算法使用
1> 求整型中位1的个数 (来自网络)
char Bit1Count (unsigned int num)
{
char c=0
while (num)
{
num &= (num-1);
c ++;
}
return c;
}
编程之美第2章2.1扩展问题2
2.给定两个正整数(二进制形式表示) A和B,问把A变为B需要改变多少位(bit)?也就是说,整数A和B的二进制表示中有多少位是不同的。
其实问题还是来求一个数中有多少个1。
问题简化:根据异或原理,同出0,异出1。可以很容易得出A和B不相同的位数都置为1,然后再求1的个数即可。
2> 用二分查找左闭右闭区间。(参考网络)
int FindLeftClosedInterval (int low, int high, char *array, char trgt)
{
int mid;
while (low < high-1)
{
mid = low + (high-low)>>1;
if (trgt > array[mid])
{
low = mid + 1;
}
else
{
high = mid;
}
}
if (array[low] >= trgt)
return low;
if (array[high] >= trgt)
return high;
return -1;
}
int FindeRightClosedInterval (int low, int high, char *array, char trgt)
{
int mid;
while (low < high-1)
{
mid = low + (high-low)>>1;
if (trgt < array[mid])
{
high = mid - 1;
}
else
{
low = mid;
}
}
if (array[high] <= trgt)
return high;
if (array[low] <= trgt)
return low;
return -1;
}
int main(int argc, char* argv[])
{
int j,k;
char array[] = {1,1,2,2,2,2,2,2,2,2,2,3,3,3,3,4,4,4,4};
j = FindLeftClosedInterval (0, sizeof(array)-1, array, 4);
k = FindeRightClosedInterval (j, sizeof(array)-1, array, 4);
printf ("j=%d.k=%d", j, k);
}
输出结果为:j=15.k=18.
3>简易的动态内存申请。
只能申请固定大小字节。嵌入式网络那些事LwIP协议深度剖析与实战演练 第6章 动态内存管理 6.2 动态内存池中方法。
#define MEMORY_POOL_NUM (3)
#define MEMORY_SIZE (32)
typedef struct _TOneMemory
{
unsigned char buffAddr[MEMORY_SIZE];
}TOneMemory;
typedef struct _TMemNext
{
struct _TMemNext *next;
}TMemNext;
typedef struct _TMemoryPool
{
TMemNext *pFirst;
void *startAddr;
void *endAddr;
TOneMemory tMemPool[MEMORY_POOL_NUM];
}TMemoryPool;
TMemoryPool g_MemPool;
void InitMemory (TMemoryPool *pPool, unsigned int MemPoolNum,unsigned int MemSize)
{
unsigned short i;
pPool->pFirst = (TMemNext *)&pPool->tMemPool[0];
pPool->startAddr = pPool->pFirst;
for (i=0; i<MEMORY_POOL_NUM-1; i++)
{
((TMemNext *)&pPool->tMemPool[i])->next = (TMemNext *)&(pPool->tMemPool[i+1]);
}
((TMemNext *)&pPool->tMemPool[i])->next = NULL;
pPool->endAddr = &pPool->tMemPool[i+1];
}
void *GetMemory ()
{
TMemoryPool *pPool = &g_MemPool;
void *addr = NULL;
if (pPool->pFirst)
{
addr = (void *)pPool->pFirst;
pPool->pFirst = pPool->pFirst->next;
}
return addr;
}
void PutMemory (void *addr)
{
TMemoryPool *pPool = &g_MemPool;
if (addr && addr>=pPool->startAddr && addr<pPool->endAddr)
{
((TMemNext*)addr)->next = pPool->pFirst;
pPool->pFirst = addr;
}
}
int main(int argc, char* argv[])
{
char *a, *b,
InitMemory (&g_MemPool, MEMORY_POOL_NUM, MEMORY_SIZE);
a = GetMemory ();
b = GetMemory ();
PutMemory (a);
PutMemory (b);
}
可以根据需要多加几种字节的动态内存分配。