bit manipulation - Move integer to the nearest divisible by 4 in C++ -


i'd move integer nearest 'divisible 4' number in c++, not if number divisible 4. here's best attempt, i'm sure suboptimal:

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

there must surely fast way of doing doesn't include tertiary if statement?

additional note: in case offset 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 need support possibility offset reference type, such size_t&. @baummitaugen.

it seems work when offset wider int without type cast, offset = (offset + 3) & ~3;, uncertain whether or not mandated language standard.


this algorithm can described in english "add 3 round down".

the rounding down part done setting 2 least significant bits 0 binary arithmetics. unsetting of bits done applying binary , inverse bit pattern, in other words make bit pattern of bits value want keep unchanged , apply mask.

binary representation of 3: 00000011

we inverse bit mask ~ (bitwise not, not confused ! logical not) operator: ~3

for ~ operator, size of operand determines size of result, on machine ~(unsigned char)3 == 252 (1111 1100) , ~(unsigned int)3 == 4294967292 (1111 1111 1111 1111 1111 1111 1111 1100). default size integer literal int.

when offset wider type (has more bits) int, need operand ~ widened bitmask matches. why cast literal 3 same type offset.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -