|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
小弟刚刚学C,遇到这个题目看不懂,求大佬们帮忙并解释下
#include <stdio.h>
void set_flag(int* flag_holder, int flag_position);
int check_flag(int flag_holder, int flag_position);
int main(int argc, char* argv[])
{
int flag_holder = 0;
int i;
set_flag(&flag_holder, 3);
set_flag(&flag_holder, 16);
set_flag(&flag_holder, 31);
for(i=31; i>=0; i--){
printf("%d", check_flag(flag_holder, i));
if(i%4 == 0){
printf(" ");
}
}
printf("\n");
return 0;
}
要求写出set_flag 和check_flag 的code
运行后结果如图
You can think of the set_flag function as taking an integer and making sure that the nth bit is a 1. The check_flag
function simply returns an integer that is zero when the nth bit is zero and 1 when it is 1. You may find the shifting
operators “<<”, and “>>” helpful as well as the bitwise operations & and |. If you find yourself using multiplication
or division in your solution then you are doing it wrong.
本帖最后由 sunrise085 于 2020-9-11 14:39 编辑
You can think of the set_flag function as taking an integer and making sure that the nth bit is a 1. The check_flag
function simply returns an integer that is zero when the nth bit is zero and 1 when it is 1. You may find the shifting
operators “<<”, and “>>” helpful as well as the bitwise operations & and |. If you find yourself using multiplication
or division in your solution then you are doing it wrong.
题目的意思:
set_flag 函数将一个 int 类型数值的第 n 个字节位设置为1。check_flag 函数简单地返回一个 int 类型数字的第 n 个字节位是1还是0,。
你应该用到左移操作符"<<"和右移操作符">>",同时可能还需要用到位逻辑运算符 & 和 | 。如果你的程序中用到了乘/除,那说明你的程序编写错了。
题目就是让你用位操作符和位运算符来完成为设置和位查询功能
- #include <stdio.h>
- void set_flag(int* flag_holder, int flag_position); // 声明函数 set_flag
- int check_flag(int flag_holder, int flag_position); // 声明函数 check_flag
- int main(int argc, char* argv[]) // 主函数
- {
- int flag_holder = 0; // 给 flag_holder 整型变量赋初值
- int i;
- set_flag(&flag_holder, 3); // 调用 set_flag 函数
- set_flag(&flag_holder, 16); // 调用 set_flag 函数
- set_flag(&flag_holder, 31); // 调用 set_flag 函数
- for(i=31; i>=0; i--) // 循环 31 次调用 printf() 输出
- {
- printf("%d", check_flag(flag_holder, i)); // 在 printf() 中调用函数 check_flag 函数的返回值
- if(i%4 == 0) // 以下四行的作用是:输出四个值后,输出一个空格
- {
-
- printf(" ");
- }
- }
- printf("\n"); // 输出一个回车
- return 0;
- }
- // 定义 set_flag 函数
- void set_flag(int* flag_holder, int flag_position)
- {
- int temp = 1;
- temp <<= flag_position; //将temp 左移 flag_position 位,即将 1 左移 flag_position 位
- *flag_holder =* flag_holder|temp; //原数值与 temp 进行位或运算,即修改第 flag_position 位为1
- }
- // 以下需要定义 check_flag 函数
- int check_flag(int flag_holder, int flag_position)
- {
- unsigned int temp = flag_holder; //将flag_holder 改为无符号整型
- temp >>= flag_position; //然后右移flag_position位,即将第 flag_position 位移动到最右边
- return temp&1; //将tenp与1进行位与运算,得到的就是第 flag_position 位的值
- }
复制代码
|
|