在学习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;
}