[英]Bitwise Operators
I'm new here but had some questions about my Computing 2 HW.我是新来的,但对我的 Computing 2 HW 有一些疑问。
Given the main function:鉴于主要功能:
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;
}
We're supposed to complete set_flag
, and check_flag
, and its supposed to display:我们应该完成
set_flag
和check_flag
,它应该显示:
1000 0000 0000 0001 0000 0000 0000 1000
Now I'm really struggling to understand this.现在我真的很难理解这一点。 is
flag_holder
supposed to equal 0 the whole time? flag_holder
应该一直等于 0 吗? My professor said to use bitwise and no multiplication.我的教授说使用按位而不是乘法。 But it looks like I could just implement an array of 32 '0's and set the 3rd, 16th, and 31st elements as 0s?
但看起来我可以实现一个包含 32 个 0 的数组并将第 3、16 和 31 个元素设置为 0? I apologize in advance for the messy set up, and thanks to any who actually read this and help!
我提前为混乱的设置道歉,并感谢任何真正阅读本文并提供帮助的人!
Let me tell you the similarity between multiplication and bitwise让我告诉你乘法和按位的相似性
left shift & right shift are used to set flags mostly左移和右移主要用于设置标志
2 = 0010
when you left shit 2 by 1, all the bits are shifted to left and with zero appended.当你把屎 2 加 1 时,所有的位都向左移动并附加零。
0010 << 1
0100
and the result will be结果将是
0100 = 4
and further left shifting make 0100
to 1000 = 8
进一步左移使
0100
到1000 = 8
left shifting is similar to multiply by 2 and right shifting is similar to divide by 2左移类似于乘以2,右移类似于除以2
Setting flags设置标志
set_flag(&flag_holder, 3);
the function will more or less be like this功能或多或少是这样的
void set_flag( int *flag_holder, int shifter) {
*flag_holder = *flag_holder | 1 << shifter;
}
what this will do is that 3rd bit is set without affecting any other bits这将做的是在不影响任何其他位的情况下设置第 3 位
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.