> 1.
> byte buffer[] = new byte[3]; //my 3-bytes-long buffer
> 2.
> res = in.read(buffer); // I read 3 bytes from file to
> put in the array
> 3.
> String bloc1 = Integer.toBinaryString(buffer[0]); // I want
Thomas Hawtin a ?crit :
> > 1.
> > byte buffer[] = new byte[3]; //my 3-bytes-long buffer
[quoted text clipped - 4 lines]
> That may not read 3 bytes. Either check res and use the read(byte[]
> buff, int off, int len) form or wrap in DataInputStream and use readFully.
I check for several iterations, including when I get negative byte..For
each loop, I really fetch 3 bytes. Not more, not less :)
> > 3.
> > String bloc1 = Integer.toBinaryString(buffer[0]); // I want
[quoted text clipped - 8 lines]
> from a byte to an int you preserve the sign to get -1 (0xffffffff). To
> get the low order octet use b & 0xff.
Yes, I believe problems come from negative numbers..
What do you mean by 'low order octet use b & 0xff' ??
I must use a 'and operation' between the byte I read and 0xff ??
thanks a lot. :)
Thomas Hawtin - 17 Dec 2006 14:43 GMT
> Thomas Hawtin a écrit :
>
>>> res = in.read(buffer); // I read 3 bytes from file to
>>> put in the array
>> That may not read 3 bytes. Either check res and use the read(byte[]
>> buff, int off, int len) form or wrap in DataInputStream and use readFully.
>
> I check for several iterations, including when I get negative byte..For
> each loop, I really fetch 3 bytes. Not more, not less :)
With something like:
int bytesRead = 0;
do {
int res = in.read(buffer, bytesRead, buffer.length);
if (res == -1) {
throw new EOFException();
}
bytesRead += res;
} while (bytesRead < buffer.length);
? I think DataInputStream.readFully is easier.
> Yes, I believe problems come from negative numbers..
> What do you mean by 'low order octet use b & 0xff' ??
> I must use a 'and operation' between the byte I read and 0xff ??
If you only want the least significant eight bits (octet) set you need
to clear the other 24 bits of the int. The obvious way to do this is
with a bitwise and operation. Another way is to shift the bits 24 to the
left and then back down (without sign extension): (b << 24) >>> 24.
Tom Hawtin