Manipulating bits

F

felixnielsen

If im not mistaken, a char variable allocates 1 byte of memory, as it
is the case with a bool variable.

I need 2 bool and 1 char variable which only need to contain a value
between 0 and 63 (times 256^3 :O)
When you consider that it makes it makes perfect sence with bit
manipulation, in case you dont understand what i mean let me give an
example.

to store a value between 0 and 63 you need only 6 bits. Lets say we
wanna store the value 27 0001 1011.
We dont need to store value greater than 63, so we can strip the 2 top
bits.
0110 11
Then lets say we wanna store a true and a false bool
1 (true)
0 (false)
And then we simply put it all together:
27 true false
011011 + 1 + 0 = 0110 1110

or another example could be to store 64 bool expressions in one
longlong?
it is ofcourse possible just to do the math but it aint allways easy
;-)

So, how to manipulate the bits?

Regards
Zacariaz
 
J

Jim Langston

If im not mistaken, a char variable allocates 1 byte of memory, as it
is the case with a bool variable.

I need 2 bool and 1 char variable which only need to contain a value
between 0 and 63 (times 256^3 :O)
When you consider that it makes it makes perfect sence with bit
manipulation, in case you dont understand what i mean let me give an
example.

to store a value between 0 and 63 you need only 6 bits. Lets say we
wanna store the value 27 0001 1011.
We dont need to store value greater than 63, so we can strip the 2 top
bits.
0110 11
Then lets say we wanna store a true and a false bool
1 (true)
0 (false)
And then we simply put it all together:
27 true false
011011 + 1 + 0 = 0110 1110

or another example could be to store 64 bool expressions in one
longlong?
it is ofcourse possible just to do the math but it aint allways easy
;-)

So, how to manipulate the bits?

Regards
Zacariaz

Well, you can use bit manipulation and bit logic.

unsigned char SomeValue = 27;
bool MyBool1 = true;
bool MyBool2 = false;

First, you want to put the 0 to 63 value in the high bits. This simply
means to shift the bits to the left twice.

unsigned char MyField = SomeValue << 2;
Now, you want to put the first bool in the 2nd LSB.
MyField = MyField | ( MyBool1 ? 2 : 0 );
Now you want to put the second bool in the most LSB.
MyField = MyField | ( MyBool2 ? 1 : 0 );

Instead of the constant 2 for MyBool1 you could use 1 << 1 for more self
documentation.

At this point I believe that MyField will contain what you want. Now to get
the values out:

SomeValue = ( Myfield >> 2 ) & 63;
The reason I and it with 63 (which is bit value 111111) is because I'm not
sure if the sign bit would be carried or not. If it does or doesn't the &
doesn't hurt.

Now for MyBool1:
MyBool1 = MyField & 2;
Any non zero value would be true. If the 2nd LSB is set MyBool1 is set to
true, otherwise it's false.
MyBool2: is just as easy.
MyBool2 = MyField & 1;

This is all bit manipulation. Look at the operators: & (bitwise and) |
(bitwise or) << (shift left) and >> (shift right).
 
F

felixnielsen

Well, come to think of it, this is pretty simple so thank you for the
answer, however there is some things that i do not understand.
For example the & operators seems pretty weird, but maybe there is some
documentation about it somewhere?
 
J

Jim Langston

Well, come to think of it, this is pretty simple so thank you for the
answer, however there is some things that i do not understand.
For example the & operators seems pretty weird, but maybe there is some
documentation about it somewhere?

& is bitwise and. It takes a left hand and a right hand operator. Any bits
set in both values will be set in the result.

I.E.
unsigned char a = 85;
unsigned char b = 76;
std::cout << a & b << std::endl;

This should output 68. The reason being, look at the bit values.

01010101 = 85
01001100 = 76
--------
01000100 = 68

Because the 64 and 4 bits were set in both, they will be set in the result.

The bit and is normally used for two different things.
1. Mask off a value. You are only interested in some part of a variable.
Set the bits you are interested in, set the rest to 0. Use that value and &
it with the value you're interested in.
2. Look to see if a certain bit is set or not. Set the value to the bit you
are interested in, the rest to zero. If the result is not zero, the bit is
set.
 
G

Gabriel

If im not mistaken, a char variable allocates 1 byte of memory, as it
is the case with a bool variable.

I need 2 bool and 1 char variable which only need to contain a value
between 0 and 63 (times 256^3 :O)
When you consider that it makes it makes perfect sence with bit
manipulation, in case you dont understand what i mean let me give an
example.

to store a value between 0 and 63 you need only 6 bits. Lets say we
wanna store the value 27 0001 1011.
We dont need to store value greater than 63, so we can strip the 2 top
bits.
0110 11
Then lets say we wanna store a true and a false bool
1 (true)
0 (false)
And then we simply put it all together:
27 true false
011011 + 1 + 0 = 0110 1110

or another example could be to store 64 bool expressions in one
longlong?
it is ofcourse possible just to do the math but it aint allways easy
;-)

So, how to manipulate the bits?

Regards
Zacariaz
I think you look for this one:

struct A
{
char c: 6; // use only 6 bit
bool b1: 1; // 1 bit
bool b2: 1; // dito
};

Gabriel
 
F

felixnielsen

oh my, something to think about... i think i got i now though, thanks
all.
One more thing thougth, if anyone can give a quick reply:
arrays vs vectors whitch is best?
i used to vector because the size can easily be increased/decreased,
however i dont need to that kinda stuff in the project im writing
rigth now, so the only obious difference between arrays and vectors, in
this case, is that multidimensional vectors are a hell of alot harder
to declare.
 
G

Gavin Deane

oh my, something to think about... i think i got i now though, thanks
all.
One more thing thougth, if anyone can give a quick reply:
arrays vs vectors whitch is best?
i used to vector because the size can easily be increased/decreased,
however i dont need to that kinda stuff in the project im writing
rigth now, so the only obious difference between arrays and vectors, in
this case, is that multidimensional vectors are a hell of alot harder
to declare.

std::vector<std::vector<int> >;

How's that hard? The only thing to remember is the space between the
two closing angle brackets. OK maybe it gets a little tedious when
you're into more than two dimensions. But it's only a little bit of
typing. And remember that you only have to declare it once. You have to
write the code that uses and manipulates the variable all over the
place. Consider how much harder that is to get correct with just a 2D
array compared to a vector of vectors, let alone anything with more
dimensions.

A little more typing in the declarations is hardly much price to pay to
completely remove the chance of introducing all those bugs you would
introduce by trying to write multi-dimensional array code by hand.

And if you still don't like the typing, use a typedef

typedef std::vector<std::vector<std::vector<int> > > vec_3D;

No contest really.

Gavin Deane


Gavin Deane
 
G

Gabriel

oh my, something to think about... i think i got i now though, thanks
all.
One more thing thougth, if anyone can give a quick reply:
arrays vs vectors whitch is best?
i used to vector because the size can easily be increased/decreased,
however i dont need to that kinda stuff in the project im writing
rigth now, so the only obious difference between arrays and vectors, in
this case, is that multidimensional vectors are a hell of alot harder
to declare.
Use a vector. Using a threedimensional array is like three people
cutting wood with chainsaws in a small pitch black room. You do want to
have the safety of vectors. If handling of threedimensional vectors
seems to cumbersome, you can use a wrapper class / util function that
transforms your 3D coordinates into a 1D vector indice.

Gabriel
 
K

Kai-Uwe Bux

oh my, something to think about... i think i got i now though, thanks
all.
One more thing thougth, if anyone can give a quick reply:
arrays vs vectors whitch is best?

std::vector is harder to mess up.
i used to vector because the size can easily be increased/decreased,
however i dont need to that kinda stuff in the project im writing
rigth now, so the only obious difference between arrays and vectors, in
this case, is that multidimensional vectors are a hell of alot harder
to declare.

No, there are more differences: a vector knows its size and supports stuff
like begin(), end(), and range checked access via at(). The interface of a
vector is better suited for the use with the algorithms in the library. If
you want a "fixed size vector", you may want to have a look into the Boost
library. If I recall correctly, it has an array container that wraps a
vector like interface around a raw array.


Best

Kai-Uwe Bux
 
F

felixnielsen

;-) thanks for the quick respons.

now only one question remains (for now ;-)

getting multiple returns from functions:
fx.

int mirror_x(int x, int y) {
return (-1*x);
return (-1*y);
(or)
return ((-1*x, (-1*y));
}

int main() {
std::cout << mirror_x(7, 5) << std::endl; // result on screen
should be -7-5
}

i used cout, that was ofcourse only to show my point, the question, is
it posible to get multiple return from one function?
 
G

Gavin Deane

;-) thanks for the quick respons.

now only one question remains (for now ;-)

getting multiple returns from functions:
fx.

int mirror_x(int x, int y) {
return (-1*x);
return (-1*y);
(or)
return ((-1*x, (-1*y));
}

int main() {
std::cout << mirror_x(7, 5) << std::endl; // result on screen
should be -7-5
}

i used cout, that was ofcourse only to show my point, the question, is
it posible to get multiple return from one function?

No. You need to pass two more int variables by reference into your
mirror function and set their values inside the function. And then the
function doesn't actually need to return anything so can be void.

This is a very basic concept. Where are you learning C++ from that
doesn't show you this?

Gavin Deane
 
G

Gabriel

;-) thanks for the quick respons.

now only one question remains (for now ;-)

getting multiple returns from functions:
fx.

int mirror_x(int x, int y) {
return (-1*x);
return (-1*y);
(or)
return ((-1*x, (-1*y));
}

int main() {
std::cout << mirror_x(7, 5) << std::endl; // result on screen
should be -7-5
}

i used cout, that was ofcourse only to show my point, the question, is
it posible to get multiple return from one function?
struct coordinate_type
{
int x;
int y;
// other useful stuff like constructor et cetera
}

coordinate_type mirror_x(coordinate_type)
{
...

(Every design problem can be solved by extra levels of abstraction
except for the 'too many levels of abstraction'-problem.)

Gabriel
 
F

felixnielsen

the thing is i dont really need to do algoritm stuff, i only need:

const int grid_size = 16;
char grid[grid_size][grid_size][grid_size];
i know where to find what im looking for and i know where to put the
stuff i need to put somewhere.
'grid[x][y][z]'
i dont need all that algoritm stuff and stuff.
it seems alot simpler to just make an array, however if nobody agrees
with me, i will take your advice and use vectors instead.
 
G

Gavin Deane

the thing is i dont really need to do algoritm stuff, i only need:

const int grid_size = 16;
char grid[grid_size][grid_size][grid_size];
i know where to find what im looking for and i know where to put the
stuff i need to put somewhere.
'grid[x][y][z]'
i dont need all that algoritm stuff and stuff.
it seems alot simpler to just make an array, however if nobody agrees
with me, i will take your advice and use vectors instead.

You can use standard library algorithms to operate on arrays, using
pointers as random access iterators. The ability to interface with all
of that extra stuff in the standard library is not what vectors give
you over arrays. The main benefit is in making it easier to write
correct code first time and easier to modify and extend code without
introducing bugs.

Depending on how simple your program is, you may get it working using
arrays quite easily. But then when you want to extend your program, or
to use similar techniques in a more complicated program, you might
start to have more difficulty.

If you can, why not try both ways as an exercise to see whether and
where vectors make life easier.

Gavin Deane
 
L

Luke Meyers

now only one question remains (for now ;-)

getting multiple returns from functions:
fx.
i used cout, that was ofcourse only to show my point, the question, is
it posible to get multiple return from one function?

No, but you have options:
1. Use output parameters -- pass the assignee in by reference, and
modify it in the function body so it has the value you want to
"return."
2. Encapsulate the information you wish to return in some kind of
special-purpose class/struct.
3. If you need to return exactly two values, consider returning a
std::pair.
4. If you need to return more than two values, consider learning about
boost::tuple. This mechanism synthesizes fixed-length heterogeneous
sequences of arbitrary magnitude, IIRC.

Luke
 
L

Luke Meyers

Gabriel said:
(Every design problem can be solved by extra levels of abstraction
except for the 'too many levels of abstraction'-problem.)

Bah, you just need to "think outside the box." ;)

Luke
 
D

Daniel T.

the thing is i dont really need to do algoritm stuff, i only need:

const int grid_size = 16;
char grid[grid_size][grid_size][grid_size];
i know where to find what im looking for and i know where to put the
stuff i need to put somewhere.
'grid[x][y][z]'
i dont need all that algoritm stuff and stuff.
it seems alot simpler to just make an array, however if nobody agrees
with me, i will take your advice and use vectors instead.

Don't just "use vectors" instead. Use a Array3D class
<http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.1
0>

Something like this should do fine:

class Array3d {
deque<char> rep; // I prefer deque because it will be easer for
// the system to find the memory for a large
int _size; // size matrix
public:
Array3d( int size ): rep( _size*_size*_size), grid_size(_size) { }

int grid_size() const { return _size; }
char& operator()( int x, int y, int z ) {
return rep[x * _size * _size + y * _size + z];
}

char operator()( int x, int y, int z ) const {
return rep[x * _size * _size + y * _size + z];
}
};

Now you can make one with:

Array3d grid( 16 );

grid(x, y, z) = 3;
 
D

Daniel T.

If im not mistaken, a char variable allocates 1 byte of memory, as it
is the case with a bool variable.

I need 2 bool and 1 char variable which only need to contain a value
between 0 and 63 (times 256^3 :O)
When you consider that it makes it makes perfect sence with bit
manipulation, in case you dont understand what i mean let me give an
example.

to store a value between 0 and 63 you need only 6 bits. Lets say we
wanna store the value 27 0001 1011.
We dont need to store value greater than 63, so we can strip the 2 top
bits.
0110 11
Then lets say we wanna store a true and a false bool
1 (true)
0 (false)
And then we simply put it all together:
27 true false
011011 + 1 + 0 = 0110 1110

or another example could be to store 64 bool expressions in one
longlong?

What you are describing is 'vector said:
it is ofcourse possible just to do the math but it aint allways easy
;-)

So, how to manipulate the bits?

The class below does what you want, but I've got to ask... Why? This
kind of low level optimization is probably not what you want to do.

class Fudge {
unsigned char _data;
public:
explicit Fudge( int a = 0, bool b = false, bool c = false ) {
_data = c + (b << 1) + (a << 2);
}

int number() const { return _data >> 2; }
bool boola() const { return (_data >> 1) & 0x1; }
bool boolb() const { return _data & 0x1; }

void number( int n ) { _data = (_data & 0x3) + (n << 2); }
void boola( bool v ) { _data = (_data & 0xFD) + (v << 1); }
void boolb( bool v ) { _data = (_data & 0xFE) + v; }
};
 

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

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,810
Latest member
Kassie0918

Latest Threads

Top