1

I just wonder how can i round to the nearest zero bitwise? Previously, I perform the long division using a loop. However, since the number always divided by a number power by 2. I decide to use bit shifting. So, I can get result like this:

12/4=3 13/4=3 14/4=3 15/4=3 16/4=4 

can I do this by performing the long division like usual?

12>>2 13>>2 

if I use this kind of bit shifting, are the behavior different for different compiler? how about rounding up? I am using visual c++ 2010 compiler and gcc. thx

4
  • I think it depends on a few factors, are you shifting signed or unsigned ints? What width? I found this link interesting for learning more about C and integers blog.regehr.org/archives/721 Commented Apr 9, 2013 at 3:35
  • ah. it's signed int (32bit) Commented Apr 9, 2013 at 3:37
  • In my experience if you write int x; int y; y = x/4; then any compiler worth a damn should convert that /4 into a bitshift for you (with optimisations turned on). Commented Apr 9, 2013 at 3:51
  • Why is floating-point involved? Commented Apr 9, 2013 at 8:14

1 Answer 1

5

Bitwise shifts are equivalent to round-to-negative-infinity divisions by powers of two, meaning that the answer is never bigger than the unrounded value (so e.g. (-3) >> 1 is equal to -2).

For non-negative integers, this is equivalent to round-to-zero.

Sign up to request clarification or add additional context in comments.

4 Comments

what do you mean by round to negative infinity? so, you are saying, the behavior produced by bitwise shifts isn't vary from one compiler to different compiler?
Provided you're using 2s-complement and arithmetic shifting for signed ints, it should be the same for all compilers.
Round to negative infinity means if the result is say 2.5 or -2.5, the rounding always makes the number smaller (to the next smaller integer), so 2.x => 2 and -2.x => -3.
Hi @nneonneo ...can you offer a source or spec sheet somewhere so I can read more about this? I'm getting into JS and using bitwise operators, and I'm trying to wrap my head around exactly how a bitwise operator will always truncate numbers after a decimal point. Yours is the first answer I've found that offers an explanation, and I'd like to know where this knowledge came from.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.