represent arrays in binary

I am developing some genetic algorithms and need to represent the content of some arrays in binary. How does one do this in c++?
There is no standard way to encode binary. The two options I know to encode a byte are either to use hexadecimal (prefix with 0x), or to use template meta programming. The template solution is not mine, but is pretty much copied straight out of the book.

1
2
3
4
5
6
7
8
9
10
template<long n>struct Binary
{
static const long value = (Binary<n/10>::value << 1) + n%10;
};

template<>
struct Binary<0>
{
static const long value = 0;
};


You can then say

 
Binary<110010>


This will equate (at compile time) to the correct value.
Last edited on
closed account (yUq2Nwbp)
also you can use bitset....it looks like this bitset<N> when N type of size_t......you can write bitset<10> b = 25;....and then print b and you'll see binary representation of 25....
I may have misunderstood the question. If you want to write binary numbers in your source file then that's what my first post was about. If you want to do bit manipulations then use std::bitset<> if you know the number of bits a compile time, and boost::dynamic_bitset<> if you don't. You can use the bitwise operators (&, |, ^, ~) with integers, but the classes are just as fast, and have a more friendly interface.
Topic archived. No new replies allowed.