5.1
题目:
略
解答代码:
1 #include <stdio.h> 2 3 int main(void) 4 { 5 char ch; 6 7 while (((ch = getchar()) != EOF) && (ch != 'z')) 8 { 9 if (ch >= 'A' && ch <= 'Z') 10 { 11 ch += 'a' - 'A'; 12 } 13 putchar(ch); 14 } 15 16 getchar(); 17 return 0; 18 }
5.2
题目:
略
解答代码:
1 #include <stdio.h> 2 3 int main(void) 4 { 5 char ch; 6 7 while (((ch = getchar()) != EOF) && (ch != 'z')) //输入z时退出 8 { 9 if (((ch >= 'A') && (ch <= 'Z')) || ((ch >= 'a') && (ch <= 'z'))) //加密 10 { 11 if ((ch <= 'M') || (ch <= 'm')) 12 { 13 ch += 'n' - 'a'; 14 } 15 else if ((ch >= 'N') || (ch >= 'n')) 16 { 17 ch -= 'n' - 'a'; 18 } 19 } 20 putchar(ch); 21 } 22 23 getchar(); 24 return 0; 25 }
5.3
题目:
编写函数,函数返回值把参数的二进制位模式从左到右变换一下后的值。
函数原型:
unsigned int reverse_bits(unsigned int value);
解答代码:
1 #include <stdio.h> 2 3 #define NUM 0xA5 4 5 unsigned int reverse_bits(unsigned int value) 6 { 7 unsigned int i; 8 unsigned int valuebak = 0; 9 char list[100] = { 0 }; 10 11 for (i=1; i!=0; i<<=1) 12 { 13 valuebak <<= 1; 14 valuebak |= (value & 0x01); 15 value >>= 1; 16 } 17 18 return valuebak; 19 } 20 21 int main(void) 22 { 23 unsigned int rev; 24 rev = reverse_bits(NUM); 25 printf("0x%X ", NUM); 26 printf("0x%X %d ", rev, rev); 27 28 getchar(); 29 return 0; 30 }
5.4
5.5
题目:
编写函数,把一个给定的值存储到一个整数中指定的几个位。假定整数中的位是从右向左进行编号,起始位的位置不会小于结束位的位置。
函数原型:
int store_bit_field(int original_value, int value_to_store, unsigned starting_bit, unsigned ending_bit);
提示:
创建一个掩码
用掩码的反码对原值AND操作
将新值左移,使与待存储值对齐
把移位后的值与掩码进行AND操作
把结果值与原值进行位OR操作
解答代码:
1 #include <stdio.h> 2 3 #define ORI_VALUE 0xFFFF 4 #define VALUE_STORE 0x123 5 #define START_BIT 13 6 #define END_BIT 9 7 8 int store_bit_field(int original_value, int value_to_store, 9 unsigned starting_bit, unsigned ending_bit) 10 { 11 unsigned int int_bit = sizeof(unsigned) * 8; 12 13 if ((starting_bit <= int_bit) && (ending_bit <= int_bit) && (ending_bit < starting_bit)) 14 { 15 unsigned int maskt = ~0; 16 unsigned int mask = 0; 17 unsigned int i; 18 19 for (i=starting_bit; i>=ending_bit; i--) //生成掩码 20 { 21 mask |= (1<<i); 22 } 23 original_value &= ~mask; 24 value_to_store <<= ending_bit; 25 value_to_store &= mask; //待存储数据与掩码匹配 26 original_value |= value_to_store; 27 } 28 else 29 printf("Data format error! "); 30 31 return original_value; 32 } 33 34 int main (void) 35 { 36 int value; 37 value = store_bit_field(ORI_VALUE, VALUE_STORE, START_BIT, END_BIT); 38 printf("0x%X ", value); 39 40 getchar(); 41 return 0; 42 }