[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppBitShifting
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.
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
CppBitShifting
(C++) Bit shifting
Quick technique for dividing and multiplying numbers.int main() { const int value1 = 64; int value2 = value1>>=1; value2>>=1; //Shift the bits of 64 to the right assert(value2 == 32); }
- include <cassert>
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.
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; }
- include <iostream>
- include <string>
Code links
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
