Re: silly unsigned/signed byte conversion question
From: Steve Horsley (steve.horsley1_at_virgin.NO_SPAM.net)
Date: 10/29/03
- Next message: Duke Hamacher: "Re: Struts 1.1 -- Generating unique URL for each JSP"
- Previous message: Roedy Green: "Re: Test login"
- In reply to: aspa: "Re: silly unsigned/signed byte conversion question"
- Next in thread: Roedy Green: "Re: silly unsigned/signed byte conversion question"
- Reply: Roedy Green: "Re: silly unsigned/signed byte conversion question"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Wed, 29 Oct 2003 20:33:00 +0000
On Wed, 29 Oct 2003 08:32:45 +0200, aspa wrote:
> Steve Horsley wrote:
>> Java has no such type as an unsigned byte.
>
> you're right. i was misleadingly trying to refer to an octet value's
> "unsigned" representation as short, int or long.
>
>> <opinion>
>> Whoever decided that byte was signed was as mad as a bucket of frogs, but
>> the deed is done now, and people will shake their heads in wonder for ever
>> more.
>
> and some of us, in confusion too :)
>
>> </opinion>
>>
>> For efficiency, I guess it is best to accept that bytes are signed, and
>> not try to convert to other types at all. If you are working with bytes,
>> then work with bytes. -128...+127. Live with it. What's the problem?
>> Instead of "if b > 127", use "if b < 0". It can be done.
>
> my original problem was reading 8-bit data from a character stream and
> then interpreting that data like in the following peace of code:
>
> File file = new File("/foo/data.d");
> int len = (int)file.length();
> byte[] buffer = new byte[len];
> FileInputStream fis = new FileInputStream(file);
> int n = fis.read(buffer, 0, len);
> fis.close();
> for(int i=0; i<n; i++) {
> int d = buffer[i] & 0xff;
> System.out.print(Integer.toHexString(d)+" ");
> }
> System.out.println();
>
> this seems to work fine, now.
It's not reliable. You have a bug.
There is no guarantee that that single read will get all the bytes in the
file in one go. You _must_ check the return value and go back for more if
the read didn't get it all. AS it is now, your program may exhibit strange
"corruption", particularly using files on network shares.
Steve
- Next message: Duke Hamacher: "Re: Struts 1.1 -- Generating unique URL for each JSP"
- Previous message: Roedy Green: "Re: Test login"
- In reply to: aspa: "Re: silly unsigned/signed byte conversion question"
- Next in thread: Roedy Green: "Re: silly unsigned/signed byte conversion question"
- Reply: Roedy Green: "Re: silly unsigned/signed byte conversion question"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|