My problem is code put below. This snippet comes from this tutorial:
http://www.youtube.com/watch?v=y71lli8MS8s.
I understand that's template of structure which generate code depending on values bitno and nbits. This structure representing register.
*nbits - is amount 1's i mask
*mask - is bit mask that consists of 1's (ex. if nbits=2 then mask=00000011)
Next part of code is overloading operators for register (struct) datatype.
*RegBit& operator=(T2 val) - overloading "=" operator
*operator unsigned() const - overloading casting operator
*RegBit& operator++ () - simple preincrementing
*unsigned operator++ (int) - postincrementing (I'm not sure ?)
I'd be grateful if you can help me to figure this snippet out line to line and explain how it works.
Most puzzling for me is idea of this scheme:
I understand that construction [ ? : ] is "if" statement and returns two possible values:
*val & mask
*!!val (LSB of val)
Sorry for my English and thanks for any help.
http://www.youtube.com/watch?v=y71lli8MS8s.
Code:
template<unsigned bitno, unsigned nbits=1, typename T=u8>
struct RegBit
{
T data;
enum { mask = (1u << nbits) - 1u };
template<typename T2>
RegBit& operator=(T2 val)
{
data = (data & ~(mask << bitno)) | ((nbits > 1 ? val & mask : !!val) << bitno);
return *this;
}
operator unsigned() const { return (data >> bitno) & mask; }
RegBit& operator++ () { return *this = *this + 1; }
unsigned operator++ (int) { unsigned r = *this; ++*this; return r; }
};
struct RegBit
{
T data;
enum { mask = (1u << nbits) - 1u };
template<typename T2>
RegBit& operator=(T2 val)
{
data = (data & ~(mask << bitno)) | ((nbits > 1 ? val & mask : !!val) << bitno);
return *this;
}
operator unsigned() const { return (data >> bitno) & mask; }
RegBit& operator++ () { return *this = *this + 1; }
unsigned operator++ (int) { unsigned r = *this; ++*this; return r; }
};
I understand that's template of structure which generate code depending on values bitno and nbits. This structure representing register.
Code:
enum { mask = (1u << nbits) - 1u };
*nbits - is amount 1's i mask
*mask - is bit mask that consists of 1's (ex. if nbits=2 then mask=00000011)
Next part of code is overloading operators for register (struct) datatype.
*RegBit& operator=(T2 val) - overloading "=" operator
*operator unsigned() const - overloading casting operator
*RegBit& operator++ () - simple preincrementing
*unsigned operator++ (int) - postincrementing (I'm not sure ?)
I'd be grateful if you can help me to figure this snippet out line to line and explain how it works.
Most puzzling for me is idea of this scheme:
Code:
data = (data & ~(mask << bitno)) | ((nbits > 1 ? val & mask : !!val) << bitno);
I understand that construction [ ? : ] is "if" statement and returns two possible values:
*val & mask
*!!val (LSB of val)
Sorry for my English and thanks for any help.