operation with bits
hi to all.
I'm new to this subject...and I would need some help.
I have the following problem:
byte[] myArray=newbyte[];
long result =0;
myArray[0]=(byte)-1;//11111111
myArray[1]=(byte)128;//10000000
result = myArray[0]+myArray[1];// should be 0000000101111111
BitSet bits =new BitSet();
for (int i=0; i<16; i++){
if (result &(1<<(i%16))) > 0){
bits.set(i);
}
}
for (int i=0; i<16; i++){
System.out.print(bits.get(15-i));
}
I would like to find the in the var result of the addition, bit to bit, of the 2 bytes
That means result transformed in 16bits should appear 0000000101111111.
But this doesn't happen. What do I do wrong?
Thanks in advance to all
[1452 byte] By [
mandy_a] at [2007-11-26 14:51:20]

> byte[] myArray= new byte[];
> long result =0;
> myArray[0]=(byte)-1;//11111111
> myArray[1]=(byte)128; //10000000
>
> result = myArray[0]+myArray[1]; // should be 0000000101111111
No it shouldn't. By default all operands are converted to ints before an
operator is applied on them/it. On top of that 'sign extension' is applied
to the operands. In your example the result is converted to type long
and again sign extension is applied.
Sign extension simply sets the sign bit of the original type as all the
other bits in the widened type, e.g.
a byte 10000000 is converted to 111111111 ... 10000000 (32 bits) in an int.
If you really need the bit pattern of a byte, mask away the 24 (32-8) bits:
int bits= aByte&0xff; // mask away bits 8 ... 31
kind regards,
Jos
result &(1<<(i%16))) has error
it should be as result & (1<<(i%16))
and what is the use (i%16) it could be simply i
and
result = myArray[0]+myArray[1]; // should not be 0000000101111111, hey for this pt i am not **** sure, Just check it . TO my idea
myArray[0]+myArray[1] will first result in a byte and then only casted to long.
hi Hunter,Ur right 127 is 01111111but 128 is not 10000000, b'coz inthe above discussion 128 is not int , it is assigned to byte, (byte) 128== -128,also what is the byte value of the bits 10000000