Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Division by two
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Binary== In binary arithmetic, division by two can be performed by a [[bit shift]] operation that shifts the number one place to the right. This is a form of [[strength reduction]] optimization. For example, 1101001 in binary (the decimal number 105), shifted one place to the right, is 110100 (the decimal number 52): the lowest order bit, a 1, is removed. Similarly, division by any [[power of two]] 2<sup>''k''</sup> may be performed by right-shifting ''k'' positions. Because bit shifts are often much faster operations than division, replacing a division by a shift in this way can be a helpful step in [[program optimization]].<ref name="WC00"/> However, for the sake of [[software portability]] and readability, it is often best to write programs using the division operation and trust in the [[compiler]] to perform this replacement.<ref>{{citation|title=Write portable code: an introduction to developing software for multiple platforms|first=Brian|last=Hook|publisher=No Starch Press|year=2005|isbn=978-1-59327-056-8|page=133}}.</ref> An example from [[Common Lisp]]: <syntaxhighlight lang="lisp"> (setq number #b1101001) ; #b1101001 β 105 (ash number -1) ; #b0110100 β 105 >> 1 β 52 (ash number -4) ; #b0000110 β 105 >> 4 β‘ 105 / 2β΄ β 6 </syntaxhighlight> The above statements, however, are not always true when dealing with dividing [[Signed number representations|signed]] binary numbers. Shifting right by 1 bit will divide by two, always rounding down. However, in some languages, division of signed binary numbers round towards 0 (which, if the result is negative, means it rounds up). For example, [[Java (programming language)|Java]] is one such language: in Java, <code>-3 / 2</code> evaluates to <code>-1</code>, whereas <code>-3 >> 1</code> evaluates to <code>-2</code>. So in this case, the compiler ''cannot'' optimize division by two by replacing it by a bit shift, when the dividend could possibly be negative.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)