简体   繁体   English

C中的按位运算:从左侧设置位

[英]Bitwise Operations in C: setting bits from left

Given an integer like 10, how could I write 10 1 bits (starting from the left) in a total of 16 bits like so: 给定一个像10这样的整数,我怎么能在总共16位中写入10位(从左边开始),如下所示:

11111111.11000000

Or given an integer like 4, it would write: 或者给出一个像4这样的整数,它会写:

11110000.00000000

Thanks, I'm still learning C and am not familiar with bitwise operations. 谢谢,我还在学习C并且不熟悉按位操作。

-(1 << wordsize - numbits) ought to do it. -(1 << wordsize - numbits)应该这样做。

It's instructive to see what happens in your example. 看看你的例子中发生了什么是有益的。 1 << wordsize - numbits is 1 << 12 , which is 00010000.00000000 . 1 << wordsize - numbits1 << 12 ,即00010000.00000000 Recalling that -x = ~x+1 , we compute ~(1 << 12) = 11101111.111111 . 回想一下-x = ~x+1 ,我们计算~(1 << 12) = 11101111.111111 Add 1 and you get 11110000.00000000 . 添加1,即可获得11110000.00000000

Actually, the int it is usually 32 bits. 实际上,int通常是32位。 But I just put 16 bits in the comments, to make it more clear. 但我只是在评论中加上16位,以使其更清晰。

int i = 0; //00000000 00000000
int mask = 65536; //10000000 00000000
int retVal = 0; //00000000 00000000
int yourAmountOfBitsToOne = 2;

for(i = 0; i < yourAmountOfBitsToOne; i++){
    retVal = retVal | (mask >> i);
}

printf("%d", retVal);

If you run this the output should be 2ˆ16 + 2ˆ15 = 98304. 如果你运行它,输出应该是216 + 215 = 98304。

Why? 为什么?

Iteration 0: 迭代0:

line 1: retVal = 00000000 00000000 | (10000000 00000000 >> 0)
line 1: retVal = 10000000 00000000

Iteration 1: 迭代1:

line 1: retVal = 10000000 00000000 | (10000000 00000000 >> 0)
line 1: retVal = 10000000 00000000 | (01000000 00000000)
line 1: retVal = 11000000 00000000 

After the for finishes, you print the integer value of 11000000 00000000 which is 98304 . 完成后,打印整数值11000000 00000000 ,即98304

Create a function now that prints the int retVal bit by bit, it will make you easy to check if the output is correct. 现在创建一个逐位打印int retVal的函数,它可以让您轻松检查输出是否正确。 And it is also a very good exercise to learn bitwise operators. 学习按位运算符也是一项非常好的练习。

Hope it helps. 希望能帮助到你。

ints are typically 32 bits. 整数通常为32位。 If you're referring to short integers, then: 如果你指的是短整数,那么:

unsigned short MakeMask16(unsigned short width,unsigned short offsetFromLeft)
{
    unsigned short mask = -1;
    mask <<= (sizeof(unsigned short)*8-width);
    mask >>= offsetFromLeft;
    return mask;
}

Or all on one line: 或全部在一条线上:

unsigned short MakeMask16(unsigned short width,unsigned short offsetFromLeft)
{
    return (unsigned short(-1<<(sizeof(unsigned short)*8-width)) >> offsetFromLeft);
}

Note that if you don't cast it to an unsigned short before right-shifting, the 1's you thought you pushed off the left will still be there. 请注意,如果你在右移之前没有将它投射到无符号的短路上,你认为你从左侧推开的1仍然会在那里。 If you don't need to offset from the left, then you can ignore that and strip away the right-shifting. 如果您不需要从左侧偏移,那么您可以忽略它并去除右移。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM