5.1

题目:

  略

解答代码:

 #include <stdio.h>

 int main(void)
{
char ch; while (((ch = getchar()) != EOF) && (ch != 'z'))
{
if (ch >= 'A' && ch <= 'Z')
{
ch += 'a' - 'A';
}
putchar(ch);
} getchar();
return ;
}

5.2

题目:

  略

解答代码:

 #include <stdio.h>

 int main(void)
{
char ch; while (((ch = getchar()) != EOF) && (ch != 'z')) //输入z时退出
{
if (((ch >= 'A') && (ch <= 'Z')) || ((ch >= 'a') && (ch <= 'z'))) //加密
{
if ((ch <= 'M') || (ch <= 'm'))
{
ch += 'n' - 'a';
}
else if ((ch >= 'N') || (ch >= 'n'))
{
ch -= 'n' - 'a';
}
}
putchar(ch);
} getchar();
return ;
}

5.3

题目:

  编写函数,函数返回值把参数的二进制位模式从左到右变换一下后的值。

函数原型:

  unsigned int reverse_bits(unsigned int value);

解答代码:

 #include <stdio.h>

 #define NUM 0xA5

 unsigned int reverse_bits(unsigned int value)
{
unsigned int i;
unsigned int valuebak = ;
char list[] = { }; for (i=; i!=; i<<=)
{
valuebak <<= ;
valuebak |= (value & 0x01);
value >>= ;
} return valuebak;
} int main(void)
{
unsigned int rev;
rev = reverse_bits(NUM);
printf("0x%X\n", NUM);
printf("0x%X\t\t%d\n", rev, rev); getchar();
return ;
}

5.4

5.5

题目:

  编写函数,把一个给定的值存储到一个整数中指定的几个位。假定整数中的位是从右向左进行编号,起始位的位置不会小于结束位的位置。

函数原型:

  int store_bit_field(int original_value, int value_to_store, unsigned starting_bit, unsigned ending_bit);

提示:

  创建一个掩码

  用掩码的反码对原值AND操作

  将新值左移,使与待存储值对齐

  把移位后的值与掩码进行AND操作

  把结果值与原值进行位OR操作

解答代码:

 #include <stdio.h>

 #define ORI_VALUE    0xFFFF
#define VALUE_STORE 0x123
#define START_BIT 13
#define END_BIT 9 int store_bit_field(int original_value, int value_to_store,
unsigned starting_bit, unsigned ending_bit)
{
unsigned int int_bit = sizeof(unsigned) * ; if ((starting_bit <= int_bit) && (ending_bit <= int_bit) && (ending_bit < starting_bit))
{
unsigned int maskt = ~;
unsigned int mask = ;
unsigned int i; for (i=starting_bit; i>=ending_bit; i--) //生成掩码
{
mask |= (<<i);
}
original_value &= ~mask;
value_to_store <<= ending_bit;
value_to_store &= mask; //待存储数据与掩码匹配
original_value |= value_to_store;
}
else
printf("Data format error!\n"); return original_value;
} int main (void)
{
int value;
value = store_bit_field(ORI_VALUE, VALUE_STORE, START_BIT, END_BIT);
printf("0x%X\n", value); getchar();
return ;
}
05-11 15:18