判别机器大小端,打印int的二进制

在学习c的位运算,有点作用的几个函数。


union int_per_byte_u{
	unsigned int value;
	unsigned char bs[4];
};


void print_per_byte(in int a)
{
	union int_per_byte_u b;
	int i;

	b.value = a;
	for( i=0; i<4; ++i ){
		printf("%d  ", b.bs[i]);
	}
	printf("\n");
}

int is_small_endian()
{
	short i = 0x0001;
	return ((char *)&i)[0];
	//[0] is low byte, [1] is high byte.
}

int is_big_endian()
{
	union int_per_byte_u b;
	b.value = 1;
	if( b.bs[0] )
		return(0);
	return(1);
	//[0] is low byte, [1] is high byte.
}

void print_binary_xx(in const char *a,in int bytes)
{
	const char *pos = a;
	int i,j;
	if( is_small_endian() ){
		for(i=bytes-1; i>=0; --i){
			for(j=7; j>=0; --j){
				printf("%d",( pos[i]&(1<<j)?1:0 ));
			}
			printf(" ");
		}
	}
	printf("\n");
}

double absolute(in double x)
{
	double tmp = x;
	*(((int *)&tmp)+1)&=0x7fffffff;
	return tmp;
	//0&1=0
	//to the high byte,highest zero is postive.
}


int align_down(in int a,in int size)
{
	return (a&~(size-1));
}


int align_up(in int a,in int size)
{
	//-b = ~(b-1);
	return ((a+size-1)&~(size-1));
}



</pre><p><pre name="code" class="cpp">int main()
{
	printf("lesson_1 hacker's book. size int %d \n", sizeof(int));
	printf("big endian:%d, small endian:%d \n",is_big_endian(), is_small_endian());
	printf("sizeof void",sizeof(void));

	//two ff is a byte
	int a=0x010204ff;
	print_binary_xx( (char *)&a, 4);

	//absolute
	double n = -1.2;
	print_binary_xx( (char *)&n, 8 );
	double abs = absolute( n );
	print_binary_xx( (char *)&abs, 8 );

	//up-down-align
	int down = align_down( 63, 16);
	int up = align_up( 63, 16 );
	printf("down align:%d, up align:%d \n",down, up);



	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值