bit operators

F

filox

not sure is it a c++ or a c question, but since i'm using c++, i'll ask
here...
i would like to use bit operators (&, |, <<), but on the type double,
because it has 64 bits. unfortunately, it seems i can't do that. can i
somehow define my own type that has the desired number of bits (i.e. using
bit fields) and then use those operators on that type?
 
A

Adrian

filox said:
not sure is it a c++ or a c question, but since i'm using c++, i'll ask
here...
i would like to use bit operators (&, |, <<), but on the type double,
because it has 64 bits. unfortunately, it seems i can't do that. can i
somehow define my own type that has the desired number of bits (i.e. using
bit fields) and then use those operators on that type?
How about using the stl bitset?

#include <iostream>
#include <bitset>

int main(char *argv[], int argc)
{
std::bitset<64> b;

b[34]=true;
b[3]=true;

std::cout << b << std::endl;

b>>=5;
std::cout << b << std::endl;

b=255;
std::cout << b << std::endl;

b&=24;
std::cout << b << std::endl;

return 0;
}


Adrian
 
G

Gianni Mariani

filox said:
not sure is it a c++ or a c question, but since i'm using c++, i'll ask
here...
i would like to use bit operators (&, |, <<), but on the type double,
because it has 64 bits. unfortunately, it seems i can't do that. can i
somehow define my own type that has the desired number of bits (i.e. using
bit fields) and then use those operators on that type?

If all you need is 64 bits, most modern compiler have a built in type.

i.e.

typedef unsigned long long bits_64;

If you need more you can define your own type e.g.

struct bits128
{
bits_64 m_lo;
bits_64 m_hi;
};

bits128 Bits( bits_64 lo, bits_64 hi )
{
bits128 retval = { lo, hi };
return retval;
}

bits128 operator|( const & bits128 lhs, const & bits128 rhs )
{
bits128 retval = { lhs.lo | rhs.lo, lhs.hi, rhs.hi };
}

.... plus a whole bunch more like this for all the other operators you need.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top