2.61 判断指定字节数据
//csapp2.61 编写表达式,下列条件下产生1,否则0,假设x是int类型,不允许使用 ==,!=
#include <stdio.h>
typedef unsigned char* byte_printer;
//打印二进制数据
void show_bytes (byte_printer start, size_t len)
{
size_t i;
for (i=0; i<len; i++)
{
printf("%.2x", *(start+i));
}
printf("\r\n");
}
//所有bit位都等于1
int all_bit_is_one(int x)
{
return !(~x);
}
//所有bit都等于0
int all_bit_is_zero(int x)
{
return !x;
}
//最低有效字节所有位都等于1
int little_byte_is_one(int x)
{
/*
* 方法一:掩码
int mask = ~0xFF;
all_bit_is_ont(x|mask);
*/
//方法二:位运算
unsigned int w = sizeof(int)<<3;
return all_bit_is_one(x<<(w-8)>>(w-8));
}
//最高有效字节,所有位都等于0
int top_byte_is_zero(int x)
{
unsigned int w = sizeof(int)<<3;
return !(x>>(w-8));
}
int main(void)
{
printf("all_bit_is_one : expect:1,result:%d\r\n", all_bit_is_one(-1));
printf("all_bit_is_one : expect:0,result:%d\r\n", all_bit_is_one(-2));
printf("all_bit_is_one : expect:0,result:%d\r\n", all_bit_is_one(0));
printf("all_bit_is_one : expect:0,result:%d\r\n", all_bit_is_one(1));
printf("all_bit_is_one : expect:0,result:%d\r\n", all_bit_is_one(2));
printf("all_bit_is_zero : expect:1,result:%d\r\n", all_bit_is_zero(0));
printf("all_bit_is_zero : expect:0,result:%d\r\n", all_bit_is_zero(-1));
printf("all_bit_is_zero : expect:0,result:%d\r\n", all_bit_is_zero(-2));
printf("all_bit_is_zero : expect:0,result:%d\r\n", all_bit_is_zero(1));
printf("all_bit_is_zero : expect:0,result:%d\r\n", all_bit_is_zero(2));
printf("little_byte_is_one(-1) : expect:1,result:%d\r\n", little_byte_is_one(-1));
printf("little_byte_is_one(0xFF) : expect:1,result:%d\r\n", little_byte_is_one(0xFF));
printf("little_byte_is_one(-2) : expect:0,result:%d\r\n", little_byte_is_one(-2));
printf("little_byte_is_one(1) : expect:0,result:%d\r\n", little_byte_is_one(1));
printf("little_byte_is_one(2) : expect:0,result:%d\r\n", little_byte_is_one(2));
printf("top_byte_is_zero(0) : expect:1,result:%d\r\n", top_byte_is_zero(0));
printf("top_byte_is_zero(1<<(w-8)) : expect:0,result:%d\r\n", top_byte_is_zero(1<<(w-8)));
return 1;
}
邮箱:quiet_learn@163.com
本文版权归作者和博客园共有,欢迎转载,转载请在文章明显位置注明作者及出处,谢谢!