In this program, I'm doing some byte/bit level management ( Im working with bits instead of bytes). In order to work with bits, I'm extracting the j-th bit, and putting it as the least significative digit of a zeroed byte. That byte goes into a list.
Here's the problematic source code. When j= 2, the program crashes
1 2 3 4 5 6 7
//buffer is an unsigned char.
//lista is list<unsigned char> lista;
//I'm trying to extract the four least significative
//bytes, insert each one in a byte containing 0 or 1
//and pushing that byte/char into lista
for(int j = 3; j>= 0; j--)
lista.push_back( (unsignedchar) (buffer&(2^j)) / (2^j) );
when j = 2, 2^j = 2^2 = 0. That's how xor works. Or did you expect a power.
I'm not sure I know what you are trying to do.
If you want to get the j-th bit from "buffer" write buffer & (1 << j)
1. ^ is not an exponentiation operator. It's exclusive OR.
2. 2j will still not give you all the bits of an integer because j doesn't go high enough.
The way this is normally done is, while the integer is not zero, you take the integer's least significant bit and push it into an array/a vector, then you right-shift the integer by 1 (which is the same as dividing by 2). Then all you do is reverse the array/vector.
Thanks for the quick answers. Effectively, i though 2^i was a power.
I don't really get what "buffer & (1 << j)" does.
(well, i actually think it does this
1 2 3
a = buffer : x x x x x x x (x represents a bit whose value is unknown)
b = 1<< j : 0 0 0 0 0 1 0 (j = 1 here)
a&b : 0 0 0 0 0 x 0 (it looks like i still need to shift right j = 1 bits)
But im not really sure)
Also i think the information provided on the tutorial about this is insufficient (which is basically what follows)
"<< SHL Shift Left
>> SHR Shift Right
"
What are the operands a, b in "a>> b" ? Is "b" the amount of bytes to shift in the memory adress of "a" or viceversa? What is inserted in the vector when shifting right/left? Zeros? Ones?
helios : If ^ is the bitewise XOR, then, is there any "power" operand? Do i have to use the math library?
Mathematically speaking, x and y being natural numbers, x<<y == x*2^y, and x>>y == x/2^y.
In reality, y is the number of bits to shift the value. 1<<1 == 10b, 11b<<1 == 110b, and so on.