用C整数移动到最近被4整除++ [英] Move integer to the nearest divisible by 4 in C++

查看:281
本文介绍了用C整数移动到最近被4整除++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个整数'被4整除号在C ++移动到就近了,但如果数量目前整除4.这是我最好的尝试,但我敢肯定,这是最理想的:

 偏移量=(偏移及3)? (偏移| 3)+1:偏移;

有肯定是这样做的快速方式,不包括第三IF语句?

附加说明:在这种情况下,偏移量是一个32位int


解决方案

 偏移量=(偏移+ 3)及〜(decltype(偏移))3;


或者

 的#include< type_traits>
// ...
偏移量=(偏移+ 3)及
    〜的static_cast<的std :: remove_reference< decltype(偏移)GT; ::类型>(3);

如果你需要支持的可能性,偏移是引用类型,如为size_t&安培; 。感谢@BaummitAugen。

这也似乎工作时偏移 INT 更宽即使没有类型转换,偏移=(偏移+ 3)及〜3; ,但我不确定是否不是由语言标准规定


这个算法可以用英文描述为加3然后舍去。

的下舍入部是由二进制算术设置为零两个最低显著位完成。位的伸出,收藏通过施加二进制和与逆位模式进行,换句话说,我们使我们希望保持不变,并且应用它作为掩模,其值的所有位的一个位模式。

二进制重新$ P $的psentation 3 00000011

我们获得与(按位NOT,不要与混淆逆位掩码!逻辑非)运算符:〜3

对于,操作数的大小决定了结果的大小,所以在我的机器〜(无符号字符)3 = = 252 1111 1100 )和〜(unsigned int类型)3 == 4294967292 1111 1111 1111 1111 1111 1111 1111 1100 )。字面的整数。缺省大小是 INT

偏移 INT 更宽的类型(有更多位),我们需要的操作数来加宽这样的掩码相匹配。这就是为什么我们投的字面 3 同类型为偏移

I'd like to move an integer up to the nearest 'divisible by 4' number in C++, but not if the number is currently divisible by 4. Here's my best attempt, but I'm sure this is suboptimal:

offset = (offset & 3) ? (offset | 3) +1 : offset;

There must surely be a fast way of doing this that doesn't include the tertiary IF statement?

Additional note: In this case offset is a 32-bit int.

解决方案

offset = (offset + 3) & ~(decltype(offset))3;


Or

#include <type_traits>
// ...
offset = (offset + 3) &
    ~static_cast<std::remove_reference<decltype(offset)>::type>(3);

if you need to support the possibility that offset is a reference type, such as size_t&. Thanks @BaummitAugen.

It also seems to work when offset is wider than int even without the type cast, offset = (offset + 3) & ~3;, but I am uncertain as to whether or not it is mandated by the language standard.


This algorithm can be described in English as "add 3 then round down".

The rounding down part is done by setting the two least significant bits to zero by binary arithmetics. Unsetting of bits is done by applying binary AND with the inverse bit pattern, in other words we make a bit pattern of all the bits whose value we want to keep unchanged and apply it as a mask.

Binary representation of 3: 00000011

We get the inverse bit mask with the ~ (bitwise NOT, not to be confused with ! logical NOT) operator: ~3

For the ~ operator, the size of the operand determines the size of the result, so on my machine ~(unsigned char)3 == 252 (1111 1100) and ~(unsigned int)3 == 4294967292 (1111 1111 1111 1111 1111 1111 1111 1100). The default size for an integer literal is int.

When offset is a wider type (has more bits) than int, we need the operand to ~ to be widened so the bitmask matches. This is why we cast the literal 3 to the same type as offset.

这篇关于用C整数移动到最近被4整除++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆