按位运算

时间:2013-01-28 03:51:23

标签: bit-manipulation bitwise-operators bit-shift

我正在使用short(我必须使用short来进行赋值,否则我只会使用int)来扫描0-31之间的值,然后使用单个整数来存储这些扫描值中的6个。

这是我到目前为止所做的:

int vals = 0;
short ndx, newVal;

/* more printing/scanning and error checking in between */

newVal = newVal << (5*ndx);
vals = vals | newVal;

当我尝试在第4或第5点放置一个有效值时,它不起作用并且只保持0 ...我想知道这是因为短的只有2个字节长所以按位左移只是得到摆脱整个价值?如果这是问题,我可以添加某种演员来修复它吗?

1 个答案:

答案 0 :(得分:0)

这正是你的想法。您使用了按位移位,然后将结果分配给一个短变量(newVal)。当你这样做时,即使计算是在32位完成,结果仍然会被截断,你只得到最低16位的0。

如果你想避免使用int,只需完全删除newVal变量,然后计算vals = vals | ((something) << (some other thing));