本文介绍了清除低位/使2的幂倍数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 确保整数是给定 2的倍数的最佳方法是什么? 怎么样 int size; ... 尺寸^ =(尺寸&(4-1)); / *确保4 * / 或 size& = -4; / *确保4 * / 的倍数? 谢谢, - John Devereux 解决方案 i = 0; 如果那不能做你想要的,你应该更清楚你的要求 。精确地定义问题通常会让你至少获得解决它的一半。 - Keith Thompson(The_Other_Keith) ks *** @ mib.org < http://www.ghoti.net/~kst> 圣地亚哥超级计算机中心< *> < http://users.sdsc.edu/~kst> 我们必须做点什么。这是事情。因此,我们必须这样做。 size - = size%4; i = 0; 如果那不是你想要的,你应该更明确地了解你的要求。正确地定义问题通常会让你至少解决它的一半。 好​​吧,你剪掉的例子应该这样做! :)但我会 尝试用文字说出来。我现在也意识到我应该使用未签名的 整数。 i是无符号整数(0,1,2,3,4,5等) n是一个编译时无符号常量整数(或字面值),它是一个 无符号整数次幂2(1,2,4,8等)。 我需要的是将我舍入到n的最接近的倍数,或者如果已经是n的倍数则保持 不变。 (该应用程序将为低级编程生成 对齐的地址)。 我知道这是相当微不足道的,我只是想知道是什么标准 成语就是为了这个。 - John Devereux Hi,What is the best way to ensure an integer is a multiple of a givenpower of 2?How aboutint size;...size ^= (size & (4-1)); /* ensure multiple of 4 */orsize &= -4; /* ensure multiple of 4 */?Thanks,--John Devereux 解决方案i = 0;If that doesn''t do what you want, you should be more explicit aboutyour requirements. Defining the problem precisely often gets you atleast halfway to solving it.--Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>We must do something. This is something. Therefore, we must do this.size -= size % 4; i = 0; If that doesn''t do what you want, you should be more explicit about your requirements. Defining the problem precisely often gets you at least halfway to solving it.Well, the examples you snipped were supposed to do that! :) But I willtry to say it in words. I also now realise I should have used unsignedints.i is an unsigned integer (0,1,2,3,4,5 etc)n is a compile-time unsigned constant integer (or literal) that is anunsigned integer power of 2 (1,2,4,8 etc).What I need is to round i down to the nearest multiple of n, or leaveunchanged if already a multiple of n. (The application is to generatealigned addresses for low-level programming).I know it''s fairly trivial, I was just wondering what the "standard"idiom was for this.--John Devereux 这篇关于清除低位/使2的幂倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-30 04:21