*2.55在你能够访问的不同机器上,使用show_bytes (文件show-bytes.c)编译并运行示例代码。 确定这些机器使用的字节顺序。
#include <stdio.h>
#include <string.h>
typedef unsigned char * byte_pointer;
void show_byte(byte_pointer x, int len);
void show_byte(byte_pointer x, int len) {
for(int i = 0; i < len; i++)
printf("%.2x ", x[i]);
//%.2x保留至少两位有效数,x表示十六进制
printf("\n");
}
运行结果:
1023
机器使用的字节顺序为:低位在低地址,故为小端
*2.56 试着用不同的示例值来运行show_bytes的代码。
exp1:
1
exp2:
23.0
exp3:
”hello”
2.57 编写程序 show_short, show_long, show_double,它们分别打印类型为 short int 、long int 、和double的C语言对象的字节表示。请试着在几种机器上运行。
void show_short(pointer x){
show_byte((byte_pointer)x,sizeof(short));
}
void show_long(pointer x){
show_byte((byte_pointer)x,sizeof(long));
}
void show_double(pointer x){
show_byte((byte_pointer)x,sizeof(double));
}
exp:
short num1=23;
long num2 =23432;
double num3=23.0;
**2.58编写过程is_little_endian,当在小端法机器上编译和运行时返回1,在大端法机器上编译运行 时则返回0。这个程序应该可以运行在任何机器上,无论机器的字长是多少。
int is_little_endian(){
uint16_t num=0X0001;
uint8_t *num2=(uint8_t*)#
if(num2[0]==1)return 1;
else return 0;
}
**2.59编写一个C表达式,使它生成一个字,由x的最低有效字节和y中剩下的字节组成。对于运算数x=0x89ABCDEF和y=0x76543210,就得到 0x765432EF。
答:
unsigned replace (unsigned x, unsigned y){
return((x&0xff)|(y&~0xff))
}
答:
unsigned put_byte(unsigned x, unsigned char b, int i){
unsigned res=0xff<<i*8;
res=(x&~res)|b<<i*8;
return res;
}
unsigned put_byte(unsigned x, unsigned char b, int i){
unsigned res=0xff<<(i<<3);
res=(x&~res)|b<<(i<<3);
return res;
}
答:
int judge(int x){
int num=(sizeof(x)-1)<<3;
return !(~x)||!(~(x-1))||!(x<<8)||!(~(x>>num))||!(x<<num);
}