首先,我想知道这是否可能:假设我有一个无符号长整数,其中包含一些未经签名的短裤,这些短整数可能也可能不在数字中。 例如:
unsigned short int id1 = 3456, id2 = 30998; unsigned long long bitfld = id1|id2;其他2个字段可以假定为0吗? 并且或者是正确的操作? 之后,假设我将bitfld作为参数传递:
void dostuff (unsigned long long bf) { //pseudo code if( the first field exists in bf) get first field; if( the second field exists in bf) get second field; //etc... }我想我必须轮询位域的前16位并检查它们,然后递归地轮询它们,验证它们并在它们大于0时存储它们。但我不确定如何做到这一点,仅移位左或右,因此,它只是划分或相乘的权利?
对不起,碰撞。 谢谢你的回答,但我最终使用了一种更简单,更高效的方法,即内部结构。 你看,我可以用一个字符串很容易地做到这一点,但我的目的是代码的用户透明,易于编程这么说。 我创建了一个内部结构来保存我的值,然后创建并返回这种结构的公共方法,所以它易于使用并且更快解析(尽管它具有在堆栈中分配(尽管很小)结构的开销,位字段解决方案没有,但唉)。
所以,谢谢大家的回答。
First of all, I want to know if this is possible: let's say I have an unsigned long which contains some abritrary unsigned shorts, which may or may not be in the number. For example:
unsigned short int id1 = 3456, id2 = 30998; unsigned long long bitfld = id1|id2;Can the other 2 fields be assumed as 0? And is OR the right operation for this? After that let's say I pass bitfld as an argument:
void dostuff (unsigned long long bf) { //pseudo code if( the first field exists in bf) get first field; if( the second field exists in bf) get second field; //etc... }I think I have to poll out the first 16 bits of the bitfield and check those, then recursively poll them, verify them and store them if they are greater than 0. But I'm not sure how to do this, bit shifting only shifts left or right, thus, it only divides or multiplies right?
sorry for the bump. Thanks all for your answers, but I ended up using a simpler and more efficient method, an internal structure. You see, I could have done this easily with a string, but my purpose was transparency to the user of the code, easy to program so to say. I created an internal structure to hold my values and then a public method to create and return such structure, so it is easy to use and faster to parse (though it has the overhead of allocating in the stack a (albeit small) structure, which the bit field solution hasn't, but alas).
So thank you all for your answers.
最满意答案
short int是2个字节长,但long long short int是8个字节,所以你有某种长度不匹配; 你可能意思是这样的:
unsigned long long bitfld = id1|(id2<<16);你可以检查是否有一个字段被AND占用:
void dostuff (unsigned long long bf) { //pseudo code if(bf & 0xFFFF) return bf & 0xFFFF; if(bf & 0xFF00) return (bf & 0xFFFF0000) >> 32; //etc... }short int is 2 bytes long, but long long is 8 bytes, so you have some kind of length mismatch; You may have meant this:
unsigned long long bitfld = id1|(id2<<16);you can check is there is a field occupied by ANDing it like:
void dostuff (unsigned long long bf) { //pseudo code if(bf & 0xFFFF) return bf & 0xFFFF; if(bf & 0xFF00) return (bf & 0xFFFF0000) >> 32; //etc... }更多推荐
发布评论