首页 文章

从InputStream解码字节

提问于
浏览
0

如果我有一个使用以下格式编码的字节流:

0x20 Length D_1 D_2 ... D_n CS

0x20...marks the beginning of a data frame
Length...number of bytes following
D_1-D_n...data bytes (interpreted as signed ints)
CS...One Byte Checksum

例:

0x20 0x05 0x01 0x02 0xD1 0xA1 0xAF
0x20 0x05 0x12 0x03 0x02 0x3A 0xF2
...
...

如何以一种常见且高效的方式从InputStream解码此字节流?我的想法是使用BufferedInputStream和以下过程(在伪代码中):

BufferedInputStream bufIS = new BufferedInputStream(mInStream); 
while (true ) {
    byte startFrame = bufIS.read(); 

    if(startFrame == 0x20) { //first byte must mark the beginning of a data frame
        int length = bufIS.read(); 
        byte dataframe[] = new bye[length];
        for (int i = 0; i<length i++) { //read data bytes
            dateframe[i] = bufIS.read(); 
        } 

    if(verifyChecksum(bufIS.read()) postEvent(dataframe); 
    } 
}

这是从InputStream接收数据帧的合适方式吗?我不能't think of a better solution for this. Also there'是一个替代的 read(byte[] b, int off, int len) 方法,它从流中读取块的字节但是不能保证读取 len 个字节,所以我认为这对我的情况没有帮助 .

2 回答

  • 0

    我使用带有自定义反序列化的ObjectInputStream .

    所以你要写一个有一个int列表并实现readObject的类,这样当给定一个输入流时,它会读取常量(并丢弃它),然后是长度,然后是n int,然后是校验和,并可选择验证它 .

    这样可以将所有代码保存在一个位置,并允许您从数据流中读取完全形成的对象 .

  • 1

    我在某个阶段做过二进制序列化工作,我们确实使用了BufferedInputStream和read()方法 . 甚至更多,因为我们使用网络流端,'len'几乎总是不受尊重 .

    我们所做的是编写我们自己的辅助方法,花了一个长度,缓冲区作为参数,然后返回那些字节,用于我们需要的解码使用 . 我们只在确定我们将在流中获得字节的全长时才使用它(只要它是我们读取的有效流)

相关问题