以下代码将L位从LSB的N个起始位置P设置为X位(N为32位数字)
//gcc 5.4.0
#include <stdio.h>
unsigned int set_bits_pos(int N, int X, int P)
{
unsigned int mask = ((1UL << X)-1) << P;
return (N|mask);
}
int main(void)
{
unsigned int bits = 3, pos=5, num=0x0F;
printf("0x%X\n", set_bits_pos(num,bits,pos));
return 0;
}
输出:
0xEF
如何转换上述功能,以将N位的X位设置为MSB的起始位置P?最好的方法。谢谢
编辑:建议后,可从MSB和独立于Arch的32和64位N进行设置
//gcc 5.4.0
#include <stdio.h>
size_t set_bits_pos(size_t N, int X, int P)
{
size_t mask = ((1UL << X)-1) << ((8*sizeof(N)) - P - X);
return (N|mask);
}
int main(void)
{
size_t num=0x0F;
int bits = 3, pos=5;
printf("0x%X\n", set_bits_pos(num,bits,pos));
return 0;
}
输出:
0x0700000F
答案 0 :(得分:0)
我建议使用精确宽度整数类型:
list = ['f','g','p','a','p','c','b','q','z','n','d','t','q'];
noOfPs = [i for i in l if i == 'p'];
noOfQs = [i for i in l if i == 'q'];
resultList= noOfPs + sorted(filter(lambda x:x not in {'q', 'p'}, l))+ noOfQs
#include <inttypes.h>
uint32_t set_low32(const uint32_t value,
const unsigned int bits,
const unsigned int skip)
{
uint32_t mask = (~(uint32_t)0) >> (32 - bits);
return value | (mask << skip);
}
uint64_t set_low64(const uint64_t value,
const unsigned int bits,
const unsigned int skip)
{
uint64_t mask = (~(uint64_t)0) >> (64 - bits);
return value | (mask << skip);
}
uint32_t set_high32(const uint32_t value,
const unsigned int bits,
const unsigned int skip)
{
uint32_t mask = (~(uint32_t)0) << (32 - bits);
return value | (mask >> skip);
}
uint64_t set_high64(const uint64_t value,
const unsigned int bits,
const unsigned int skip)
{
uint64_t mask = (~(uint64_t)0) << (64 - bits);
return value | (mask >> skip);
}
是要设置的位数(有问题的bits
,而X
是要跳过的低/高位数(有问题的skip
)