下列输出的值:
#include <stdio.h> int func(){ static int count = 1; return ++count; } int main() { int answer = 0; answer = func() - func() * func(); printf("%d\n", answer); return 0; }
answer = 2 - 3 * 4;
所以结果 -10;
5.3 编写函数 unsigned int reverse_bits(unsigned int value);将二进制模式从左到右变换,输入25输出2 550 136 832
#include <stdio.h> //反转bit位 unsigned int reverse_bits(unsigned int value) { unsigned int result = 0; unsigned int tmp = 1; //计算unsigned int位数 int len = sizeof(unsigned int) * 8; int idx; //每次向右位偏移一位 for(idx = 0; idx < len; idx++){ //判断bit值,如果是1 if(((value >> idx)) & 1){ //则将tmp中对应的另一端的位置为1 tmp = 1 << (len - idx - 1); //tmp和result取或运算置位1 result |= tmp; } } return result; } //将value二进制形式打印出来 void print_bits(unsigned int value) { int len = sizeof(unsigned int) * 8; int idx; int bit; for(idx = 1; idx <= len; idx++){ //从左往右,通过位偏移后,和1取与运算,打印bit位的值 bit = 1 & (value >> (len - idx)); printf("%d", bit); //四位一空,方便阅读 if(idx % 4 == 0){ printf(" "); } } printf("\n"); } int main() { unsigned int input = 25; unsigned int result; printf("%d\n", input); print_bits(input); result = reverse_bits(input); printf("%u\n", result); print_bits(result); return 0; }
输出:
25 0000 0000 0000 0000 0000 0000 0001 1001 2550136832 1001 1000 0000 0000 0000 0000 0000 0000
5.5把给定的值存储到一个整数中指定的几个位
#include <stdio.h> int store_bit_field(int original_value, int value_to_store, unsigned starting_bit, unsigned ending_bit) { int mask = 0; int tmp = 0; //制作对应的起始位置掩码 for(int idx = starting_bit; idx >= ending_bit; idx--){ tmp = 1 << idx; mask |= tmp; } //通过掩码将original_value 对应的范围内置0 original_value &= ~mask; //将value_to_store对齐起始和结束位置 value_to_store <<= ending_bit; //value_to_store中将超出范围的部分置0 value_to_store &= mask; //将值和original_value取或保存值 original_value |= value_to_store; return original_value; } int main() { int result; result = store_bit_field(0xffff, 0x123, 13, 9); printf("0x%0x\n", result); return 0; }
输出:
oxc7ff
时间: 2024-10-24 12:43:27