1. 程式人生 > >指標,位元位操作

指標,位元位操作

為了找工作,最近在看《程式設計師面試寶典》第四版,發現之前學習C++都是太膚淺了。原來位元位操作還可以很靈活的運用哈...

1.用一個表示式判斷一個數X是不是2的N次方(N為整數),不可用迴圈語句。

!(X&(X-1))

2.不使用任何中間變數,交換a和b的值。

a = a^b;

b = a^b;

a = a^b;

3.指標和基於位元位運算的小演算法

#include <stdio.h>
#include <cmath>

int f(int x, int y)
{
	return (x&y) + ((x^y)>>1);//實質功能:求取兩個整數的均值
}

int Add(int x, int y)
{
	if (y == 0)
	{
		return x;
	}
	int sum, carry;
	sum = x^y;             //第一步沒有進位的加法運算
	carry = (x&y)<<1;      //第二步進位並且左移運算
	return Add(sum,carry);
}

inline int Max(int x, int y)
{
	return ((x+y) + abs(x-y))/2;//選擇兩個整數中最大數,新思路
}

inline int max(int a, int b) {return a>=b? a:b;}
inline int min(int a, int b) {return a<=b? a:b;}
inline int medium(int a, int b, int c)
{
	int t1 = max(a,b);
	int t2 = max(b,c);
	int t3 = max(a,c);
	return min(t1,min(t2,t3));
}
int main()
{
	unsigned int a = 0xFFFFFF7;
	unsigned char i = (unsigned char)a;
	
	char* b = (char*)&a;
	/*
	* 等價於:
	* unsigned int *p = &a;
	* char* b = (char*)p;
	*/
	printf("No.1 Pointer problem:\n");
	printf("%08x, %08x \n", i, *b);

	printf("No.2 MeanAdd problem:\n");
	int meanX = f(729,271);
	int addX = Add(2,8);
	printf("%d, %d\n", meanX, addX);


	printf("No.3 Max problem:\n");
	int maxv = Max(3,5);
	printf("%d\n",maxv);

	printf("No.4 Median problem:\n");
	int medianv = medium(3,7,9);
	printf("%d\n",medianv);

	return 0;
}