开发者

InputStream reading trouble

I have the following problem: I have to read from an InputStream a sequence of data but due its own arrangement I need to read the first 4 bytes as an unsigned short (16 bits) so in this way I will read two blocks of two bytes because the meaning of those bytes are numbers开发者_StackOverflow社区 but after that I need to read as an unsigned byte because the meaning of all the remaining data is ASCII.

Someone could advice me on how to accomplish that?


You can use java's own DataInputStream. You can read the first 4 bytes by using readInt, the rest using just readByte... See http://download.oracle.com/javase/6/docs/api/java/io/DataInputStream.html


There's no unsigned short in Java, all numbers in java are signed, you will need an int to store an unsigned short. and as @chicharo pointed out, an unsigned short will only occupy 2 bytes of memory, not 4 bytes.

The following code will do what you want:

int number = inputStream.read() | (intputStream.read() << 8);
byte[] buffer = new byte[2048];
int lenRead = 0;
while ((lenRead = inputStream.read(buffer)) != -1) {
    // write lenRead bytes each time to somewhere, like a ByteArrayOutputStream..
    ......
}

Note: I assumed you wrote your number in that order that lower bits get written first.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜