I am at a total loss as to why this doesn't work
int temp[2];
int shift;
shift = temp[0]
shift = shift<<3>>3;
I am trying to 0 the upper bytes to extract the value stored in bits 0-4. The result value is higher than 32. How can this be?
I am at a total loss as to why this doesn't work
int temp[2];
int shift;
shift = temp[0]
shift = shift<<3>>3;
I am trying to 0 the upper bytes to extract the value stored in bits 0-4. The result value is higher than 32. How can this be?
>shift = shift<<3>>3;
Here you shift the bits first 3 bits to left and then back to 3. Assuming an int is 4 bytes, 32 bits, probably on ly the last 3 bits will be set to zero.
If you want to get the value of the first 3 bits and want to use bit-operators, there are other ways, then you could do something like this.
111 (bin) = 7 (dec)
So you could define a mask like this:
#define FIRST_3_BITS_MASK 0x07
And get the value like this:
shift = shift & FIRST_3_BITS_MASK;
>shift = shift<<3>>3;
You are not trying to zeor the higher bits here, though might just work in a few cases. To zero the desired bits, use the & (AND) Operator.
shift = shift & 0xf0;
will give you the higher 4 bits of the variable shift.
Which bits exactly do you want??
I can't visualize them like that
post them like this:
<- Highbits Lowbits->
00001111 00000000 00000000 00000000
shift/fill warning.
The shift operators << and >> perform left and right shifts of their left
operand by the number of bit positions given by the left operand.
Thus x << 2 shifts the value of x left by two positions and x >> 2 shifts
the value right by two positions.
Left shifting always fills vacated bits with zero.
Right shifting an unsigned quantity always fills vacated bits with zero.
Right shifting a signed quantity will fill the sign bits ("arithmatic shift")
on some machines and with 0 bits ("logical shift") on others.
ex:
if x = 4
both cases yield a binary 16Code:x = x << 2; or x <<= 2;
Definition taken out of K&R second edition page 49.
Last edited by jerryvtts; 07-15-2002 at 12:09 AM.