2.55 2.56 2.57
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef unsigned char * byte_pointer;
void show_bytes(byte_pointer start, size_t len)
{
size_t i;
for (i = 0; i < len; i++)
printf(" %.2x", start[i]);
printf("\n");
}
void show_int(int x){
show_bytes((byte_pointer) &x, sizeof(int));
}
void show_float(float x){
show_bytes((byte_pointer) &x, sizeof(float));
}
void show_pointer(void *x){
show_bytes((byte_pointer) &x, sizeof(void *));
}
void show_short(short x){
show_bytes((byte_pointer) &x, sizeof(short));
}
void show_long(long x){
show_bytes((byte_pointer) &x, sizeof(long));
}
void show_double(double x){
show_bytes((byte_pointer) &x, sizeof(double));
}
void test_show_bytes(int val){
int ival = val;
float fval = (float) ival;
short sval = (short) ival;
long lval = (long) ival;
double dval = (double) ival;
int *pval = &ival;
show_int(ival);
show_float(fval);
show_pointer(pval);
show_short(sval);
show_long(lval);
show_double(dval);
}
int main(void)
{
test_show_bytes(15213);
printf("\n");
test_show_bytes(666);
return 0;
}
2.58
int is_little_endian()
{
int x = 1;
byte_pointer p = &x;
return p[0];
}
2.59
return ((x & 0xFF) | (y & ~0xFF));
2.60
unsigned replace_byte(unsigned x, int i, unsigned char b)
{
int j;
unsigned char c;
j = 8 * i;
b = b << j;
c = (~0xFF) << j;
return ((x & c) | b);
}
2.61
#include<stdio.h> /* 包含测试部分 */
// A:
int is_INT_MAX(int x){
return !(x + 1);
}
// B:
int is_ZERO(int x){
return !(x - 0);
}
// C:
int is_low_byte(int x){
x = x & 0xFF;
return !(x - 0xFF);
}
// D:
int is_high_byte(int x){
return !(x & (0xFF << 24));
}
int main(void) // 测试
{
int a = 0;
int b = 0xFFFFFFFF;
int c = 0x123456FF;
int d = 0x00123456;
printf("%d\n", is_INT_MAX(a));
printf("%d\n", is_INT_MAX(b));
printf("%d\n", is_INT_MAX(c));
printf("%d\n