所以这是代码:
int create_mask(unsigned b, unsigned e)
{
unsigned int mask=1;
if(b<e || b<0 || e<0)
{
printf("Wrong values, starting bit can't be smaller than ending.\n");
printf("Both got to be >= 0.\n");
exit(EXIT_FAILURE);
}
while(b>0)
{
printf("%u\n", b);
mask<<=1;
if(b>e)
mask|=1;
b--;
}
return ~mask; /* negates mask for later purpose that is clearing corresponding bits */
}
该函数用于创建一些位操作的掩码,但应该接受两个无符号整数b和e,均为非负数。问题是如何防止用户输入负数?当该函数被调用时,如果传入(-1, 0),它会开始循环,并应该因错误而退出。
(-1, 0)
。输入一个字符串,然后使用strtoul()
将其转换为无符号整数。如果数字为负数,它会报告错误。 - user5297581 << width
,其中width
是一个unsigned int
中的位数。 - user529758