Re: binary format of the number.
Tarmo Kuuse a ?crit :
blargg wrote:
If you really want binary, you can write a macro (or template) that
accepts four 8-bit chunks, something like
BIN(00000011,11000000,00000000,00000000).
Can you point to a sound compile time implementation of such
macro/template? I'd be interested.
Sorry, ignore my previous post. I thought you wanted to output it in a
stream in bin format.
With binary defined as follow:
template<typename T=unsigned,int nbbit=8>
struct binary
{
//initialize octet with binary form long
binary(long v)
{
T exp=1;
val=0;
//ensure v in range 0 11111111
v%=11111112;
//build value
while(v)
{
ldiv_t d=ldiv(v,10); //ldiv from stdlib.h C99
v=d.quot;
if(d.rem)val|=exp;
exp*=2;
}
}
//initialize octet with pre-computed value
struct value
{
T val;
value(T v):val(v){}
};
explicit binary(const value& v):val(v.val){}
operator T()const{return val;}
T val;
};
//concatenate binaries
template<typename T,int nbbit_lhs,int nbbit_rhs>
binary<T,nbbit_lhs+nbbit_rhs> operator<<(
const binary<T,nbbit_lhs>& lhs,
const binary<T,nbbit_rhs>& rhs)
{
typedef binary<T,nbbit_lhs+nbbit_rhs> binary_type;
return binary_type(
typename binary_type::value(
(lhs.val<<nbbit_rhs)|rhs.val
)
);
}
Example:
std::cout<<(binary<>(1)<<binary<>(101))<<std::endl;
int cons=binary<int>(10000000)binary<int>(0);
You can improve of the template expression such as:
* binary(int val,int number) to build representation of number with
only 0s or 1s in a given number at given position.
* using fills fill<int,24>(1) -> 111...11 24 bits
And so on.
--
Michael