[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppBitShifting

(C++) Bit shifting

Quick technique for dividing and multiplying numbers.

  1. include <cassert>
int main() { const int value1 = 64; int value2 = value1>>=1; value2>>=1; //Shift the bits of 64 to the right assert(value2 == 32); }


Biological example

From http://richelbilderbeek.nl/CppInheritance.htm:

Code snippet of a function to convert an integer to a std::string of zeroes and ones. Also it shows an example of bitwise manipulation often used in biology: If the genome of a kid's offspring consists of 0's and 1's only, then you only need one integer to generate to offspring's genome.

  1. include <iostream>
  2. include <string>
std::string intToBitString(int bits) { std::string s; if (bits==0) return "00000000"; while (bits>0) { s = (bits % 2 ? "1" : "0") + s; bits>>=1; } while (s.size() % 8) { s = "0" + s; } return s; } int main() { const int mother = 15; //00001111 const int father = 240; //11110000 const int inherit = 170; //10101010 ---> 0 denotes: inherits from mother, 1: inherits from father //Results should be 10100101 const int kid = (mother & (~inherit)) | (father & inherit); std::cout << intToBitString(mother) << std::endl; std::cout << intToBitString(father) << std::endl; std::cout << intToBitString(inherit) << std::endl; std::cout << intToBitString(kid) << std::endl; }


Code links



last edited (February 21, 2007) by bilderbikkel, Number of views: 9805, Current Rev: 7 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Site Management by Lars Hagelin at Kontantkort.se.