[英]How to set the mask based on the different values of lengths using C program
In a function I have to pass the bitlength and based on the bit length the mask will be set. 在一个函数中,我必须传递位长,然后根据位长设置掩码。 For example here is my part of program 例如,这是我程序的一部分
if(length == 8)
mask = 0xff;
if(length == 7)
mask = 0x7f;
if(length == 12)
mask = 0x3ff;
if(length == 16)
mask = 0xffff;
How can I use some loop statements to set the mask as the length varies from 1 to 16? 当长度从1到16不等时,如何使用一些循环语句设置掩码? It would be great if someone helps, thanks in advance. 如果有人帮助,那就太好了,谢谢。
How to set the mask based on the different values of lengths using C program? 如何使用C程序基于不同的长度值设置掩码?
Shift 1u by n
, then subtract 1. No loop needed. 将1u移n
,然后减去1。不需要循环。 Best to use unsigned types and guard against a large length
with a mask to insure no undefined behavior (UB). 最好使用无符号类型,并使用掩码防止较大的length
,以确保没有未定义的行为 (UB)。
#define UINT_WIDTH 32
unsigned length = foo();
unsigned mask = (1u << (length & (UINT_WIDTH - 1)) - 1u;
How can I use some loop statements to set the mask as the length varies from 1 to 16? 当长度从1到16不等时,如何使用一些循环语句设置掩码?
This works well for [1 ... UINT_WIDTH]
. 这对于[1 ... UINT_WIDTH]
效果很好。
If using fixed width types like uint16_t
, then set the ..._WIDTH
mask to 16. 如果使用固定宽度类型(如uint16_t
,则将..._WIDTH
掩码设置为16。
For portable code, UINT_WIDTH
needs to be consistent with unsigned
. 对于可移植代码, UINT_WIDTH
必须与unsigned
一致。
#include <limits.h>
#if UINT_MAX == 0xFFFF
#define UINT_WIDTH 16
#elif UINT_MAX == 0xFFFFFFFF
#define UINT_WIDTH 32
#elif UINT_MAX == 0xFFFFFFFFFFFFFFFF
#define UINT_WIDTH 64
#else
// Very rare
#error TBD code
#endif
Start with a value of zero. 从零开始。 Then for every bit in the mask, shift left by 1 then OR a 1 bit at the end. 然后,对于掩码中的每个位,向左移1,然后在末尾向左移1。
uint16_t mask = 0;
for (int i = 0; i < length; i++) {
mask <<= 1;
mask |= 1;
}
You can do it like the following: 您可以按照以下方式进行操作:
uint16_t mask = 0;
for (size_t i = 0; i < length; i++)
mask |= (1 << i);
For each iteration of the loop, you or |
对于循环的每次迭代,您或|
your mask
with a bit shifted by i
position to the left. 你的mask
带着几分偏移了i
位置的左边。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.